Мне нужно создать универсальный набор, в котором я могу передать classname.classname.property и значение, которое нужно установить. Я видел этот вопрос и был дан ответ, но я не могу реализовать его в своем проекте.SetValue для свойств из унаследованного класса
ссылка 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);
}
}