我想要做一個簡單的表達示例獲取屬性的名稱。這是一個簡單的教程,通過圍繞C#表達式包裝我的頭腦。麻煩包裝我的頭在c中使用表達式#
我有以下代碼:
public class TestClass
{
public string TestProperty { get; set; }
}
class Program
{
static void Main(string[] args)
{
TestClass test = new TestClass();
string name = GetPropertyName(() => test.TestProperty);
Console.WriteLine("Property name is: ");
Console.ReadLine();
}
public string GetPropertyName(Expression<Func<object, object>> expression)
{
var memberExp = expression.Body as MemberExpression;
if (memberExp == null)
throw new InvalidOperationException("Not a member expression");
return memberExp.Member.Name;
}
}
這將產生2個問題:
1)當撻打字string name = GetPropertyName
智能感知實際上並沒有顯示我GetPropertyName()
方法。
2)() => test.TestProperty
給出Delegate 'System.Func<object,object>' does not take 0 arguments
我一直在嘗試使用http://marlongrech.wordpress.com/2008/01/08/working-with-expression-trees-part-1/和http://jagregory.com/writings/introduction-to-static-reflection/作爲教程/引用編譯錯誤,但我絕對不理解的東西。
呵呵,謝謝:) – KallDrexx 2011-04-14 19:10:43