2009-11-03 81 views

回答

6

您可以使用表達式輕鬆實現此目的。看到這個blog for a sample

這使得您可以通過拉姆達創建表達式,並取出名稱。例如,實施INotifyPropertyChanged的可以修改,以做類似:

public int MyProperty { 
    get { return myProperty; } 
    set 
    { 
     myProperty = value; 
     RaisePropertyChanged(() => MyProperty); 
    } 
} 

爲了映射你的等效,使用所引用的「反映」級,你會做這樣的事情:

string propertyName = Reflect.GetProperty(() => SomeProperty).Name; 

中提琴 - 沒有魔術字符串的屬性名稱。

+0

這裏的語法有點討厭,但它確實做了我所需要的。謝謝! – 2009-11-03 20:53:02

1

您可以使用反射來獲取對象的屬性列表。

MyClass o; 

PropertyInfo[] properties = o.GetType().GetProperties(
    BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance 
); 

每個屬性都有一個名稱屬性,它會讓你 「SomeProperty」

8

這種方法會比使用Expression

public static string GetName<T>(this T item) where T : class 
{ 
    if (item == null) 
     return string.Empty; 

    return typeof(T).GetProperties()[0].Name; 
} 

現在這樣快,你可以把它叫做:

new { MyClass.SomeProperty }.GetName(); 

如果需要更多性能,可以緩存值。看到這個重複的問題How do you get a variable's name as it was physically typed in its declaration?

+0

這裏的最佳答案。我不想循環屬性,我想根據實際屬性獲取屬性名稱。使用具有第一個(唯一)屬性的匿名類型是您想要的名稱是天才。 – Paul 2014-06-12 14:15:29

+0

@保羅我不是它背後的天才。其次,它不是非常重構友好的。我的意思是如果你改變屬性的名字,匿名類型保留原來的名字。在這種情況下,如果將'SomeProperty'更改爲'SomeProperty1',則匿名類將更改爲'new {SomeProperty = SomeProperty1}',將打印「SomeProperty」,而不是更新的名稱「SomeProperty1」。我會在答案中提到它。 – nawfal 2014-06-12 14:50:12

+0

織補。我預計不會更改屬性名稱,但如果我曾經這樣做,我會希望重構來處理它。謝謝你讓我知道。 – Paul 2014-06-12 16:03:34

相關問題