2015-09-01 3 views
0

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

ответ

0

Вы пытаетесь установить значение строкового объекта вкуса. Он отлично работает, используя новый экземпляр 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); 
    } 
} 
Смежные вопросы