C# 反射 - 获取没有字符串的 PropertyInfo [英] C# Reflection - Get PropertyInfo without a string

查看:35
本文介绍了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);

这篇关于C# 反射 - 获取没有字符串的 PropertyInfo的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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