2011-08-14 24 views
0

如何實現此getter和setter?它會使用方法而不是屬性嗎?還是不可能?屬性和方法的字符串表示形式

SomeClass someObject = new SomeClass(); 
int x = someObject.GetProperty("X"); 
someObject.SetProperty("Y","Value"); 
someObject.Call("DoSomething"); 


class SomeClass 
{ 
    public int X{ get; set; } 
    public string Y{ get ;set; } 
    public void DoSomething() { return; } 
} 

回答

3

,你將需要使用Reflection對於這樣的事情 - 例如:

SomeClass someObject = new SomeClass(); 

int x = someObject.GetType().GetProperty ("X").GetGetMethod().Invoke (someObject,null); 

somObject.GetType().GetProperty("Y").GetSetMethod().Invoke(someObject, new object[] { "Value" }); 

someObject.GetType().GetMethod("DoSomething").Invoke(someObject, null); 
+0

怎麼樣的一些參數的方法? –

+0

點擊鏈接(反射)在我的答案,那裏你會發現幾個樣本,包括「帶參數的方法」... – Yahia

1

是的,你可以使用反射:

SomeClass sc = new SomeClass(); 
Type scType = sc.GetType(); 
PropertyInfo xProp = scType.GetProperty("X"); 
xProp.SetValue(sc, 7, null); // sets sc.X = 7 
相關問題