【问题标题】:select for dynamic result选择动态结果
【发布时间】:2014-10-09 01:43:57
【问题描述】:

我无法完成这项工作,我有动态结果,我需要选择它到一个新对象。

var getMethod = SubType.BaseType.BaseType.GetMethod("List").MakeGenericMethod(SubType);

dynamic result = getMethod.Invoke(null, new object[] { UId.ToGuid() });

return ((IEnumerable)result.Value).Select(c => new { c.UId, Text = GetPropertyValue(c, SubText) });

【问题讨论】:

    标签: c# linq dynamic


    【解决方案1】:

    这并不容易。您还必须将Reflection 用于Select。您需要使用MakeGenericMethod 传递SubType 并获得Select 的正确重载。

    然后您还需要创建一个Func<> 委托,然后将其传递给 Select 的 Invoke 方法。我建议您创建一个命名类型而不是选择匿名类型,然后创建一个 Func 会更容易。您可以找到更多信息here 关于如何通过Reflection 创建委托类型。

    下面是一些示例代码:

    var select = typeof (Enumerable)
            .GetMethods(BindingFlags.Static | BindingFlags.Public)
            .First(m => m.Name == "Select" &&
                        m.GetParameters()[1].ParameterType.GetGenericArguments().Length == 2);
    
    var selectMethod = select.MakeGenericMethod(typeof(SubType));
    
    var func = typeof(Func<>).MakeGenericType(SubType, ResultType);
    
    ...
    

    【讨论】:

    • 我认为我的编程技能还不够:(
    【解决方案2】:

    尝试将最后一行更改为:

    return ((IEnumerable)result.Value).Select(c => new { UId = c.UId, Text = GetPropertyValue(c, SubText) });
    

    动态对象的所有属性都需要命名。

    【讨论】:

      猜你喜欢
      • 2012-01-12
      • 2021-02-21
      • 1970-01-01
      • 2010-12-28
      • 2013-03-29
      • 1970-01-01
      • 1970-01-01
      • 2021-04-15
      • 2018-11-03
      相关资源
      最近更新 更多