2012-11-08 66 views
-3

有沒有辦法用變量引用屬性名稱?請參閱變量的屬性名稱

場景:對象A具有公共整數屬性X的Z,所以......

public void setProperty(int index, int value) 
{ 
    string property = ""; 

    if (index == 1) 
    { 
     // set the property X with 'value' 
     property = "X"; 
    } 
    else 
    { 
     // set the property Z with 'value' 
     property = "Z"; 
    } 

    A.{property} = value; 
} 

這是一個愚蠢的例子,所以請相信,我對這個的使用。

+0

很難理解你想要完成什麼。 –

+0

您可以使用System.Reflection 這樣做例如,請參閱此http://stackoverflow.com/questions/619767/net-reflection-set-object-property。 –

+2

我很好奇爲什麼你會做這樣的事情而不是像財產一樣使用財產? – Jared

回答

19

簡單:

a.GetType().GetProperty("X").SetValue(a, value); 

注意GetProperty("X")返回null如果a型沒有名爲 「X」 的屬性。

要在您提供的語法設置屬性只寫一個擴展方法:

public static class Extensions 
{ 
    public static void SetProperty(this object obj, string propertyName, object value) 
    { 
     var propertyInfo = obj.GetType().GetProperty(propertyName); 
     if (propertyInfo == null) return; 
     propertyInfo.SetValue(obj, value); 
    } 
} 

而且使用這樣的:

a.SetProperty(propertyName, value); 

UPD

需要注意的是這種反思基於方法相對較慢。爲了獲得更好的性能,使用動態代碼生成或表達式樹有很好的庫可以爲你做這個複雜的東西。例如,FastMember

3

我想你的意思反射...

像:

PropertyInfo info = myObject.GetType().GetProperty("NameOfProperty"); 
info.SetValue(myObject, myValue); 
4

不是你的建議,但是它是可行的。您可以使用dynamic對象(或者甚至僅使用屬性索引器的對象),例如

string property = index == 1 ? "X" : "Z"; 
A[property] = value; 

或者通過使用反射:

string property = index == 1 ? "X" : "Z"; 
return A.GetType().GetProperty(property).SetValue(A, value); 
0

這是我很難理解你想實現...如果你想分別確定屬性和值什麼,在不同的時間,你可以將設置屬性的行爲包裝在委託中。

public void setProperty(int index, int value) 
{ 
    Action<int> setValue; 

    if (index == 1) 
    { 
     // set property X 
     setValue = x => A.X = x; 
    } 
    else 
    { 
     // set property Z 
     setValue = z => A.Z = z; 
    } 

    setValue(value); 
}