如何使用typeof运算或的GetType()作为通用的模板? [英] How to use typeof or GetType() as Generic's Template?

查看:92
本文介绍了如何使用typeof运算或的GetType()作为通用的模板?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果这是很难用语言来解释,让我们来看一个例子 我有这样一个泛型函数

If it's harder to explain using words, let's look at an example I have a generic function like this

void FunctionA<T>() where T : Form, new()
{
}

如果我有一个反射式,我怎么使用它与上面的功能?我期待着这样做。

If I have a reflected type, how do I use it with the above function? I'm looking forward to do this

Type a = Type.GetType("System.Windows.Forms.Form");
FunctionA<a>();

原因上面的方法是行不通的。

Of cause the above method doesn't work.

推荐答案

您不能。在.NET泛型必须在编译时解决。你试图做一些事情,将解决他们在运行时。

You can't. Generics in .NET must be resolved at compile time. You're trying to do something that would resolve them at runtime.

你能做的唯一一件事就是提供一个重载泛函,需要一个类型的对象。

The only thing you can do is to provide an overload for FunctionA that takes a type object.


嗯......他是一个家伙,但他是对的。

Hmmm... he's a dick, but he's right.

class Program
{
    static void Main(string[] args)
    {
        var t = typeof(Foo);
        var m = t.GetMethod("Bar");
        var hurr = m.MakeGenericMethod(typeof(string));
        var foo = new Foo();
        hurr.Invoke(foo, new string[]{"lol"});
        Console.ReadLine();
    }
}

public class Foo
{
    public void Bar<T>(T instance)
    {
        Console.WriteLine("called " + instance);
    }
}

<一个href="http://msdn.microsoft.com/en-us/library/system.reflection.methodinfo.makegenericmethod.aspx">MakeGenericMethod.

这篇关于如何使用typeof运算或的GetType()作为通用的模板?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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