C# 反射 - 获取没有字符串的 PropertyInfo

C# 反射 - 获取没有字符串的 PropertyInfo

问题描述:

我在 Myclass 中有一个属性:

I have a property in Myclass:

public class MyClass{    
    public string FirstName {get;set;}
}

如何在没有字符串的情况下获取 PropertyInfo(使用 GetProperty("FirstName"))?

How can I get the PropertyInfo (using GetProperty("FirstName")) without a string?

今天我用这个:

PropertyInfo propertyTitleNews = typeof(MyClass).GetProperty("FirstName");

有没有这样的使用方法:

Is there a way for use like this:

PropertyInfo propertyTitleNews = typeof(MyClass).GetProperty(MyClass.FirstName);

?

参见 此处.这个想法是使用表达式树.

See here. The idea is to use Expression Trees.

public static string GetPropertyName<T, TReturn>(Expression<Func<T, TReturn>> expression)
{
    MemberExpression body = (MemberExpression)expression.Body;
    return body.Member.Name;
}

然后像这样使用它:

var name = GetPropertyName<MyClass, string>(c => c.FirstName);

如果不需要指定这么多通用参数,那么更简洁的解决方案将是.并且可以通过将 MyClass 通用参数移动到 util 类:

A bit cleaner solution would be if one would not required to specify so much generic parameters. And it is possible via moving MyClass generic param to util class:

public static class TypeMember<T>
{
    public static string GetPropertyName<TReturn>(Expression<Func<T, TReturn>> expression)
    {
        MemberExpression body = (MemberExpression)expression.Body;
        return body.Member.Name;
    }
}

然后使用会更干净:

var name = TypeMember<MyClass>.GetPropertyName(c => c.FirstName);