c# - 是否可以将属性名称作为字符串传递并为其赋值?

标签 c# .net 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

实现可能是这样的:

C#/VB.NET

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

这是否可能无需根据提供的 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);
    }
}

如果您需要经常执行此操作,就性能而言可能会非常痛苦。委托(delegate)有一些技巧可以使它更快,但值得先让它工作。

关于c# - 是否可以将属性名称作为字符串传递并为其赋值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3443194/

相关文章:

c# - 接受两个接口(interface)之一的方法

c# - AssemblyInfo 版本信息星号

asp.net - <#=#>是什么意思

vb.net - Linq to SQL中的Sum和Group By?

c# - : Conversion operators cannot convert from an interface type如何解决

sql-server - 如何在repeater vb.net中基于下拉列表绑定(bind)数据

c# - 在配置文件中使用引号作为值

c# - Delphi 到 C# WinForms : Iterate through form components on form

c# - 使用javascript将paypal隐藏字段的值设置为asp控件的值

c# - C# :Cross-thread operation not valid: Control 'lblp4' accessed from a Cross-thread operation not valid 中的线程异常错误