2011-04-14 22 views
0

我想要做一個簡單的表達示例獲取屬性的名稱。這是一個簡單的教程,通過圍繞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/作爲教程/引用編譯錯誤,但我絕對不理解的東西。

回答

2

首先,System.Func<object,object>表示您的lambda表達式接受一個object類型的參數並返回一個對象,因此您將擁有一個表達式,如(arg) => test.PropertyName。如果您不想輸入參數,請使用System.Func<object>

其次,您在Intellisense中看不到您的GetPropertyName方法,因爲Main是一個static方法。或者創建一個Program對象的實例並從那裏調用它,或者將GetPropertyName聲明爲static

+0

呵呵,謝謝:) – KallDrexx 2011-04-14 19:10:43