c# - 反射 - 获取属性名称

标签 c# reflection

<分区>

我想在不使用魔术字符串的情况下将属性名称传递给函数。

类似于:

Get<ObjectType>(x=>x.Property1);

其中 Property1 是 ObjectType 类型的属性。

方法实现是什么样的?

最佳答案

这可以使用表达式来实现:

// requires object instance, but you can skip specifying T
static string GetPropertyName<T>(Expression<Func<T>> exp)
{
    return (((MemberExpression)(exp.Body)).Member).Name;
}

// requires explicit specification of both object type and property type
static string GetPropertyName<TObject, TResult>(Expression<Func<TObject, TResult>> exp)
{
    // extract property name
    return (((MemberExpression)(exp.Body)).Member).Name;
}

// requires explicit specification of object type
static string GetPropertyName<TObject>(Expression<Func<TObject, object>> exp)
{
    var body = exp.Body;
    var convertExpression = body as UnaryExpression;
    if(convertExpression != null)
    {
        if(convertExpression.NodeType != ExpressionType.Convert)
        {
            throw new ArgumentException("Invalid property expression.", "exp");
        }
        body = convertExpression.Operand;
    }
    return ((MemberExpression)body).Member.Name;
}

用法:

var x = new ObjectType();
// note that in this case we don't need to specify types of x and Property1
var propName1 = GetPropertyName(() => x.Property1);
// assumes Property2 is an int property
var propName2 = GetPropertyName<ObjectType, int>(y => y.Property2);
// requires only object type
var propName3 = GetPropertyName<ObjectType>(y => y.Property3);

更新:已修复 GetPropertyName<TObject>(Expression<Func<TObject, object>> exp)对于返回值类型的属性。

关于c# - 反射 - 获取属性名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4657311/

相关文章:

c# - 使用ZeroMQ通过Internet进行客户端/服务器通信

从 VB 转换的 C# 不起作用

java - 反射 Class.forName() 找到类 <classname>$1 和 <classname>$2,它们是什么?

c# - 无法连接到蓝牙打印机

c# - 从类访问表单控件?

c# - 我可以通过编程方式确定接口(interface)要求/依赖关系/继承吗?

c# - 是否可以在不使用 MVC 的情况下访问 DisplayName 属性?

javascript - 如何通过名称调用私有(private)函数

c# - 为什么 Azure 表存储不支持 DateTimeOffset?

java - 获取字段名称