c# - 使用 System.Type 中的泛型类型调用泛型方法

标签 c# .net generics reflection byref

下面是一个代码示例和问题,请注意我不能使用 C# 4.0 和 dynamic 关键字。

static class TestClass
{
    static void Main(string[] args)
    {
        Object o = "Previous value";
        Test(ref o);
        Trace.WriteLine(o);
    }

    static public void Test<T>(ref T obj)
    {
        //  The goal is to somehow invoke Test2 with the real type of obj, i.e the type in obj.GetType() 

        //  1st try:
        Test2(ref obj); // This doesn't work because the type in Test2 will be the same as T here.

        //  2nd try:
        MethodInfo mi = typeof(TestClass).GetMethod("Test2");
        mi = mi.MakeGenericMethod(new Type[] { obj.GetType() });
        mi.Invoke(null, new Object[] { obj }); // obj is no longer by reference so we need to store the object array and copy back the result after the call

        //  3rd try, successful implementation by the smartest mind of stack overflow :)
    }

    static public void Test2<T>(ref T s)
    {
        if (typeof(T) == typeof(String))
        {
            s = (T)(Object)"Hello world!";
        }
    }
}

我还尝试了一些使用 Delegate.CreateDelegate 的方法,但没有成功。 这有可能吗?

编辑:我不害怕使用动态方法(和 MSIL 汇编程序),但我在这方面的知识非常有限。

Edit2:这是一个更接近我真正尝试做的例子:

public static class TypeHandler<T>
{
    public delegate void ProcessDelegate(ref T value);

    public static readonly ProcessDelegate Process = Init();

    private static ProcessDelegate Init()
    {
        //  Do lot's of magic stuff and returns a suitable delegate depending on the type
        return null;
    }
}


static class TestClass
{
    static public void Main(string[] args)
    {
        Object o = "Previous value";
        Test(ref o);
        Trace.WriteLine(o);
    }

    static public void Test<T>(ref T obj)
    {
        if (obj is T)
        {
        //  Optimized, common case
            TypeHandler<T>.Process(ref obj);
            return;
        }
        Type t = obj.GetType();
        //  How to call the delegate found in TypeHandler<t>.Process ? (I can get delegate but I can't call it).


    }

}

最佳答案

您的评论看起来您已经了解如何去做:

MethodInfo mi = typeof(TestClass).GetMethod("Test2");
mi = mi.MakeGenericMethod(new Type[] { obj.GetType() });
object[] args = new object[] { obj };
mi.Invoke(null, args);
obj = (T) args[0];

这实际上只是将您的评论转化为代码。这会不会以某种方式无法满足您的要求?

关于c# - 使用 System.Type 中的泛型类型调用泛型方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8357454/

相关文章:

c# - Ninject - 如何在范围内保存常量?

c# - 如何在 UIThread 上测试 Prism 事件聚合器订阅?

c# - 您将如何构建 HttpTraceListener?

asp.net - .net SqlCommandTimeOut 和连接池

c# - 使用泛型将字符串值转换为枚举并简单地将字符串值转换为枚举时的混淆

c# - 获取 Active Directory 中的组成员列表 (memberOf)

c# - Nullable<T> 的装箱/拆箱行为如何可能?

c# - 在 GTK# Image Widget 中显示动画 GIF

delphi - 从泛型参数继承在 Delphi XE 中不起作用

c# - 将泛型类型的实例返回到在运行时解析的函数