Is it possible to pass in a property name as a string and assign a value to it?

后端 未结 3 1872
终归单人心
终归单人心 2021-01-12 18:11

I\'m setting up a simple helper class to hold some data from a file I\'m parsing. The names of the properties match the names of values that I expect to find in the file.

3条回答
  •  一向
    一向 (楼主)
    2021-01-12 18:53

    In terms of organizing the code, you could do it in a mixin-like way (error handling apart):

    public interface MPropertySettable { }
    public static class PropertySettable {
      public static void SetValue(this MPropertySettable self, string name, T value) {
        self.GetType().GetProperty(name).SetValue(self, value, null);
      }
    }
    public class Foo : MPropertySettable {
      public string Bar { get; set; }
      public int Baz { 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);
      }
    }
    

    This way, you can reuse that logic in many different classes, without sacrificing your precious single base class with it.

    In VB.NET:

    Public Interface MPropertySettable
    End Interface
    Public Module PropertySettable
       _
      Public Sub SetValue(Of T)(ByVal self As MPropertySettable, ByVal name As String, ByVal value As T)
        self.GetType().GetProperty(name).SetValue(self, value, Nothing)
      End Sub
    End Module
    

提交回复
热议问题