我需要创建一个通用的set accesor,我可以传递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);
}
}
答案 0 :(得分:0)
您正在尝试将字符串值设置为Taste对象。 使用Taste的新实例
可以正常工作class Program {
static void Main() {
var foo = new Foo();
foo.SetValue("Bar", new Taste());
foo.SetValue("Baz", 42);
Console.WriteLine("{0} {1}", foo.Bar, foo.Baz);
}
}
如果BarSize派生自MPropertySettable,它将起作用。
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 : MPropertySettable
{
public int length { get; set; }
public int width { get; set; }
}
class Program
{
static void Main() {
var barSize = new BarSize();
barSize.SetValue("length", 100);
barSize.SetValue("width", 42);
Console.WriteLine("{0} {1}", barSize.length, barSize.width);
}
}