【问题标题】:Invoke generics overloaded method using reflection使用反射调用泛型重载方法
【发布时间】:2013-10-27 17:43:48
【问题描述】:

我需要使用反射调用重载方法。 我的课程如下:

public static Transformer
{
    //Overloaded method with generics parameter. First Transform Method
    public  static TranformerResult  Transform<T>(object [] entities,
        List<T>  dataContract) where T:class
    {
        return transformerResult;
    }

    //Overloaded method without generics parameter. Second Transform Method
    public static TranformerResult  Transform(object  entities,
        Type dataContract) 
    {
        return transformerResult;
    }
}   

public class TransformerResult
{
    public List<T> GetTypes<T>() where T:class
    {
    }
}

我尝试使用以下语法调用第一个 Transform 方法:

GetMethod(“Transform”,(BindingFlags.Static | BindingFlags.Public),
    null, new Type[](){typeof(object[]),typeof(List<Type>}, null)

但是我得到了第二个 Transform 方法。

我的意图是在 transformerResult 上调用 GetType。 TransformerResult 是一个返回第一个转换方法调用的对象。

谁能帮我写 C# 代码来实现我的意图?

谢谢, 马希尔

【问题讨论】:

    标签: c# reflection


    【解决方案1】:

    您遇到问题的原因是您正在寻找的特定方法是通用的。该方法的其中一种类型基于该方法的通用参数。这为您提供了一些注意事项 22。泛型参数与方法相关联,因此在您拥有方法本身之前,您无法正确构造该方法的类型数组。

    针对这种特定场景的一个解决方案是直接获取第一个通用方法。

    var method = typeof(Transformer).GetMethods().Where(x => x.IsGenericMethod).First();
    

    【讨论】:

      【解决方案2】:

      除非这行得通:typeof(List&lt;&gt;) 你将需要对你所做的事情有点棘手,类似于我对这篇文章所做的事情:http://www.aaron-powell.com/posts/2010-04-08-reflection-and-generics.html

      本质上是使用 LINQ 搜索所有 Transform 方法的集合,你不能只返回你想要的原生方法。

      【讨论】:

      • 您发布的链接现已损坏。
      • @PeterO。链接是固定的
      【解决方案3】:

      我认为调用GetMethod() 的类型数组中的第二种类型令人困惑。如果您获得包含这些方法的类的 Type 类的实例,则不包括用于创建该类实例的实际泛型参数(根据您的第二个代码示例,它看起来像 Type )。相反,它只知道它有一个通用参数。

      我目前没有编译器,所以很遗憾我不能尝试这个,但我会尝试为第二个参数指定 typeof(List&lt;T&gt;) 的等效项(你也许能够得到这个致电System.Collections.Generic.List.GetType(),但我并不肯定)。

      如果这不起作用,我能想到的唯一其他选择是调用Type.GetMethods(BindingFlags.Static | BindingFlags.Public),然后自己搜索数组。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-11-27
        相关资源
        最近更新 更多