使用反射调用泛型重载方法 [英] Invoke generics overloaded method using reflection

查看:125
本文介绍了使用反射调用泛型重载方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要使用反射来调用重载方法。
我班如下:

I need to invoke an overloaded method using reflection. My classes as below:

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
    {
    }
}

我试图调用先用变换方法的语法如下:

I tried to invoke first Transform method with below syntax:

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

但我正在逐渐第二变换方法。

But I am getting second Transform method.

我的目的是要调用的GetType上transformerResult该transformerResult是对象,返回调用第一个变换方法。

My intention is to invoke GetType on transformerResult . The transformerResult is an object which returns invocation of first transform method.

任何一个可以帮我写C#代码来实现我的意图?

Can any one help me to write the C# code to achieve my intention?

谢谢,
的Mahir

Thanks, Mahir

推荐答案

您正在运行到一个问题的原因是,特定的方法你要找的是通用的,其中一个类型的方法是基于该方法的泛型参数的。这给你一个有点追赶22的泛型参数是联系在一起的方法,所以你不能正确地构建该方法的类型数组,直到你有方法本身。

The reason you're running into a problem is that the particular method you're looking for is generic. One of the types of the method is based off of the generic parameter of the method. This presents you with a bit of a catch 22. The generic parameter is tied to the method so you cannot properly construct the type array for the method until you have the method itself.

此特定场景刚刚抢了先泛型方法的一种解决方案。

One solution for this specific scenario is the just grab the first generic method.

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

这篇关于使用反射调用泛型重载方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆