是否有可能在属性名传递作为字符串和值分配给它? [英] Is it possible to pass in a property name as a string and assign a value to it?
问题描述
我设置了一个简单的辅助类来保存从文件中我分析一些数据。属性的名称相匹配,我希望找到的文件中值的名称。我想一个名为 AddPropertyValue
方法添加到我的课,这样我可以分配一个值的属性,而不按名称显式调用它。
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. I'd like to add a method called AddPropertyValue
to my class so that I can assign a value to a property without explicitly calling it by name.
该方法是这样的:
//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
的实施可能是这样的:
The implementation might look like this:
C#/ VB.NET
C#/VB.NET
MyHelperClass.AddPropertyValue("LocationID","5")
这是可能的,而无需测试对每个单独的属性名称所提供的 propertyName的
?
推荐答案
您可以做到这一点与反思,通过调用 Type.GetProperty
然后 PropertyInfo.SetValue
。你需要做适当的错误处理,检查的财产实际上并不存在present虽然。
You can do this with reflection, by calling Type.GetProperty
and then PropertyInfo.SetValue
. You'll need to do appropriate error handling to check for the property not actually being present though.
下面是一个示例:
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);
}
}
如果你需要做这个有很多,它可以成为在性能方面相当痛苦。大约有代表它可以使快了不少招数,但它的价值得到它的工作第一。
If you need to do this a lot, it can become quite a pain in terms of performance. There are tricks around delegates which can make it a lot faster, but it's worth getting it working first.
这篇关于是否有可能在属性名传递作为字符串和值分配给它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!