2010-08-09 56 views
5

我设置了一个简单的帮助类来保存我解析文件中的一些数据。这些属性的名称与我期望在文件中找到的值的名称相匹配。我想为我的类添加一个名为AddPropertyValue的方法,以便我可以将值赋给某个​​属性,而不必按名称明确调用它。是否有可能将属性名称作为字符串传递并为其分配值?

的方法是这样的:

//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 

实现可能是这样的:

C#/ VB.NET

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

这是可能的,而不必测试每个个别物业名称与提供的propertyName

+0

非常相似,这个以前的帖子:http://stackoverflow.com/questions/110562/how-to-pass-a-generic-property-as-a-参数对函数 – David 2010-08-09 18:54:48

回答

7

您可以通过调用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's 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); 
    } 
} 

如果你需要做这个有很多,它可以成为在性能方面相当痛苦。围绕代表的技巧可以让代表更快,但值得让它首先工作。

4

使用反射您使用的名称获得属性并将其值设置......是这样的:

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

在组织代码的条款,你可以做一个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); 
    } 
} 

这样,您可以在许多不同的类中重用该逻辑,而不会牺牲您的宝贵单一基类。

在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 
+1

而对于get:public static string GetValue(this IPropertySettable self,string name) { return self.GetType()。GetProperty(name).GetValue(self,null).ToString() ; } – 2016-07-18 16:17:35

相关问题