0
我有存储函数的字典。 虽然存储Func(testDir.Add(1,p => p.Id))很好。当我从字典中获得Func时,我想要存储在Func中的属性(Id)的名称。 我曾试过Retrieving Property name from lambda expression Get property name and type using lambda expression此链接。它在简单的Func中工作。但与字典我得到成员= null在GetMemberInfo。想要Func参数名称不是值,存储在字典
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");
}
static void Main(string[] args)
{
Dictionary<int, Func<Soure.Employee, int>> testDir = new Dictionary<int, Func<Soure.Employee, int>>();
testDir.Add(1, p => p.Id);
var testDirValue = testDir[1];
Expression<Func<Soure.Employee, int>> expr1 = mc => testDirValue(mc);
MemberInfo member = Program.GetMemberInfo(expr1);
Console.WriteLine(member.Name);
}
感谢阿萨德。然后如何执行存储在Expression中的Func。 –
@HemantMalpote为了从'Expression'中获得'Func',只需使用'Compile'方法。 'Func idGetter = testDir [1] .Compile(); int id = idGetter(someEmployee);'。 –