如何实现此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; }
}
答案 0 :(得分: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);
答案 1 :(得分:1)
是的,您可以使用反射:
SomeClass sc = new SomeClass();
Type scType = sc.GetType();
PropertyInfo xProp = scType.GetProperty("X");
xProp.SetValue(sc, 7, null); // sets sc.X = 7