【发布时间】:2014-12-22 07:16:50
【问题描述】:
我有存储 Funct 的字典。 在存储 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。但是有了字典,我在 GetMemberInfo 中得到 member = null。
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);
}
【问题讨论】: