且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用 lambda 表达式获取属性名称和类型

更新时间:2022-06-27 05:53:11

这里有足够的使用 表达式 获取属性或字段的名称以帮助您入门:

Here's enough of an example of using Expressions to get the name of a property or field to get you started:

public static MemberInfo GetMemberInfo<T, U>(Expression<Func<T, U>> expression)
{
    var member = expression.Body as MemberExpression;
    if (member != null)
        return member.Member;

    throw new ArgumentException("Expression is not a member access", "expression");
}

调用代码如下所示:

public class Program
{
    public string Name
    {
        get { return "My Program"; }
    }

    static void Main()
    {
        MemberInfo member = ReflectionUtility.GetMemberInfo((Program p) => p.Name);
        Console.WriteLine(member.Name);
    }
}

但是要注意:(Program p) => 的简单语句p.Name 实际上涉及相当多的工作(并且可能需要大量时间).考虑缓存结果而不是频繁调用方法.

A word of caution, though: the simple statment of (Program p) => p.Name actually involves quite a bit of work (and can take measurable amounts of time). Consider caching the result rather than calling the method frequently.