【发布时间】:2015-09-06 03:13:11
【问题描述】:
我需要创建一个通用集访问器,我可以在其中传递 classname.classname.property 和要设置的值。 我看到了这个问题并得到了回答,但我无法在我的项目中实现它。
链接是Is it possible to pass in a property name as a string and assign a value to it?
在下面的示例代码中,SetValue如何设置长度和宽度的值?
public interface MPropertySettable { }
public static class PropertySettable {
public static void SetValue<T>(this MPropertySettable self, string name, T value) {
self.GetType().GetProperty(name).SetValue(self, value, null);
}
}
public class Foo : MPropertySettable {
public Taste Bar { get; set; }
public int Baz { get; set; }
}
public class Taste : BarSize {
public bool sweet {get; set;}
public bool sour {get; set;}
}
public class BarSize {
public int length { get; set;}
public int width { get; set;}
}
class Program {
static void Main() {
var foo = new Foo();
foo.SetValue("Bar", "And the answer is");
foo.SetValue("Baz", 42);
Console.WriteLine("{0} {1}", foo.Bar, foo.Baz);
}
}
【问题讨论】: