SetValue для свойств от унаследованного класса

Мне нужно создать общий набор аксессуаров, в котором я могу передать имя класса.classname.property и значение, которое нужно установить. Я видел этот вопрос и получил ответ, но не могу реализовать его в своем проекте.

ссылка Можно ли передать имя свойства в виде строки и присвоить ему значение?

Как в приведенном ниже примере кода 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);
  }
}

person queque    schedule 01.09.2015    source источник


Ответы (1)


Вы пытаетесь установить строковое значение для объекта 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);
    }
}
person Sagi    schedule 05.09.2015