使用 lambda 表达式获取属性名称和类型 [英] Get property name and type using lambda expression

查看:45
本文介绍了使用 lambda 表达式获取属性名称和类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个函数,该函数将使用如下语法提取属性名称和类型:

I am trying to write a function that will pull the name of a property and the type using syntax like below:

private class SomeClass
{
    Public string Col1;
}

PropertyMapper<Somewhere> propertyMapper = new PropertyMapper<Somewhere>();
propertyMapper.MapProperty(x => x.Col1)

有没有什么方法可以将属性传递给函数而不对该语法进行任何重大更改?

Is there any way to pass the property through to the function without any major changes to this syntax?

我想获取属性名称和属性类型.

I would like to get the property name and the property type.

所以在下面的例子中我想检索

So in the example below i would want to retrieve

Name = "Col1"Type = "System.String"

有人可以帮忙吗?

推荐答案

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

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.

这篇关于使用 lambda 表达式获取属性名称和类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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