【问题标题】:Want Func parameter name not the value, stored in dictionary希望 Func 参数名称而不是值,存储在字典中
【发布时间】: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);
        }

【问题讨论】:

    标签: c# linq


    【解决方案1】:

    expr1 中的表达式实际上并不包含 p =&gt; p.Id 的表达式树。它包含 lambda mc =&gt; testDirValue(mc) 的表达式树,这是一个由对不透明委托的调用组成的表达式。无法从第二个 lambda 中获取有关访问了哪个属性的信息。

    您想要的信息被编码为 lambda 文字语法。一旦它作为任意委托存储和检索,此信息将不再可用。您真正想要做的是将Expression&lt;Func&lt;Soure.Employee, int&gt;&gt; 存储在您的字典中,以便从您添加到字典中的 lambda 构建表达式树:

    var testDir = new Dictionary<int, Expression<Func<Soure.Employee, int>>>();
    testDir.Add(1, p => p.Id);
    MemberInfo member = GetMemberInfo(testDir[1]);
    Console.WriteLine(member.Name); // Id
    

    【讨论】:

    • 谢谢阿萨德。那么如何执行存储在Expression中的Func。
    • @HemantMalpote 要从Expression 返回Func,只需使用Compile 方法。 Func&lt;Soure.Employee, int&gt; idGetter = testDir[1].Compile(); int id = idGetter(someEmployee);.
    猜你喜欢
    • 1970-01-01
    • 2017-07-16
    • 1970-01-01
    • 1970-01-01
    • 2016-10-21
    • 2022-08-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多