通过变量引用属性名称 [英] Refer to a property name by variable

查看:74
本文介绍了通过变量引用属性名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以使用变量来引用属性名称?

Is there a way to refer to a property name with a variable?

场景:对象A具有公共整数属性X和Z,所以...

Scenario: Object A have public integer property X an Z, so...

public void setProperty(int index, int value)
{
    string property = "";

    if (index == 1)
    {
        // set the property X with 'value'
        property = "X";
    }
    else 
    {
        // set the property Z with 'value'
        property = "Z";
    }

    A.{property} = value;
}

这是一个愚蠢的例子,所以请相信,我对此很有用.

This is a silly example so please believe, I have an use for this.

推荐答案

简单:

a.GetType().GetProperty("X").SetValue(a, value);

请注意,如果 a 的类型没有名为"X"的属性,则 GetProperty("X")返回 null .

Note that GetProperty("X") returns null if type of a has no property named "X".

要使用您提供的语法设置属性,只需编写一个扩展方法:

To set property in the syntax you have provided just write an extension method:

public static class Extensions
{
    public static void SetProperty(this object obj, string propertyName, object value)
    {
        var propertyInfo = obj.GetType().GetProperty(propertyName);
        if (propertyInfo == null) return;
        propertyInfo.SetValue(obj, value);
    }
}

并像这样使用它:

a.SetProperty(propertyName, value);

UPD

请注意,这种基于反射的方法相对较慢.为了获得更好的性能,请使用动态代码生成或表达式树.有很好的库可以为您完成这些复杂的工作.例如, FastMember .

Note that this reflection-based method is relatively slow. For better performance use dynamic code generation or expression trees. There are good libraries that can do this complex stuff for you. For example, FastMember.

这篇关于通过变量引用属性名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆