[C#] C# Exrpession 好好玩之動態指定 Property 並且設定值

  • 3259
  • 0
  • 2016-02-15

C# Exrpession好好玩之動態指定 Property 並且設定值

前陣子才知道在C#裡面有Expression這種東西,不過其實要怎麼用這個namespace下的東西並不是很清楚 之前同事有用ExpressionFunc的一個簡單東西,可以去取得Property的「名字」

public static string GetName<T>(this Expression<Func<T>> property)
{
  string name = string.Empty;
 
  MemberExpression member = property.Body as MemberExpression;
  if (member != null) {
    name = member.Member.Name;
  }
  
  return name;
}

這樣簡單的用途可以用在Dictionary就可以用Property當做Key,dictionary.Add(ReflectionUtility.GetName(() => PropertyA), PropertyA); 可以省去一點Hardcode,並且如果PropertyA改名稱,Dicionary也會一併的改 今天由Expression延伸另外一個想法,我可以用這個去動態指定一個Property並設定值給它嗎?是可以的,網路上有許多種寫法,有簡單的也有複雜的,今天我嘗試出來的算是比較簡單的一種


public class PageViewModel
{
  public string P1 { get;set;}
  public string P2 { get;set;}

  public void Foo(int condition, string value)
  {
    Expression<Func> selectedProperty;
    if (condition > 0) {
      selectedProperty = () => P1;
    }
    else {
      selectedProperty = () => P2;
    }

    var expression = selectedProperty.Body as MemberExpression;
    var propertyInfo = expression.Member as PropertyInfo;
    propertyInfo.SetValue(this, value);
  }
}

上面是個簡單的範例,可以讓一些重複「動作」的程式碼簡化,不過上面的作法其實用Reflection做就可以啦XD 就只是玩玩看Expression