【问题标题】:SetValue to properites from inherited class将值设置为继承类的属性
【发布时间】: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);
  }
}

【问题讨论】:

    标签: system.reflection


    【解决方案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);
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-03-09
      • 2015-07-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-26
      • 2013-05-17
      相关资源
      最近更新 更多