Ben*_*ack 6 .net c# vb.net reflection
我正在设置一个简单的帮助器类来保存我正在解析的文件中的一些数据.属性的名称与我期望在文件中找到的值的名称相匹配.我想添加一个调用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
Run Code Online (Sandbox Code Playgroud)
实现可能如下所示:
C#/ VB.NET
MyHelperClass.AddPropertyValue("LocationID","5")
Run Code Online (Sandbox Code Playgroud)
这是否可能无需针对提供的每个单独的属性名称进行测试propertyName
?
您可以通过反射,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);
}
}
Run Code Online (Sandbox Code Playgroud)
如果你需要做很多事情,它在性能方面会变得非常痛苦.代表们之间的技巧可以让它快得多,但值得让它先工作.