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

I am creating a simple helper class to store some data from a file that I am processing. Property names correspond to the names of the values ​​that I expect to find in the file. I would like to add a method with a name AddPropertyValuein my class so that I can assign a value to a property without explicitly calling it by name.

The method will look like this:

//C#
public void AddPropertyValue(string propertyName, string propertyValue) {
   //code to assign the property value based on propertyName
}

---

'VB.NET'
Public Sub AddPropertyValue(ByVal propertyName As String, _
                            ByVal propertyValue As String)
    'code to assign the property value based on propertyName '
End Sub

An implementation might look like this:

C # / vb.net

MyHelperClass.AddPropertyValue("LocationID","5")

Is it possible without having to check each individual property name for the supplied one propertyName?

+5
source share
3 answers

, Type.GetProperty, PropertyInfo.SetValue. , , .

:

using System;
using System.Reflection;

public class Test
{
    public string Foo { get; set; }
    public string Bar { get; set; }

    public void AddPropertyValue(string name, string value)
    {
        PropertyInfo property = typeof(Test).GetProperty(name);
        if (property == null)
        {
            throw new ArgumentException("No such property!");
        }
        // More error checking here, around indexer parameters, property type,
        // whether it read-only etc
        property.SetValue(this, value, null);
    }

    static void Main()
    {
        Test t = new Test();
        t.AddPropertyValue("Foo", "hello");
        t.AddPropertyValue("Bar", "world");

        Console.WriteLine("{0} {1}", t.Foo, t.Bar);
    }
}

, . , , , .

+7

, ... - :

Type t = this.GetType();
var prop = t.GetProperty(propName);
prop.SetValue(this, value, null);
+4

, mixin-like ( ):

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 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);
  }
}

That way you can reuse this logic in many different classes without sacrificing your valuable base class.

In VB.NET:

Public Interface MPropertySettable
End Interface
Public Module PropertySettable
  <Extension()> _
  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
+2
source

All Articles