获取属性名称和使用lambda前pression型 [英] Get property name and type using lambda expression
问题描述
我想写这将拉属性的名称和使用的语法像下面的类型的函数:
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
谁能帮助?
推荐答案
下面是使用足够的防爆pressions ,以得到一个属性或字段的名称,让你开始:
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");
}
调用code是这样的:
Calling code would look like this:
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);
}
}
要提醒一句,虽然:(程序P)的简单说明书=&GT; 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前pression型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!