本文介绍了通用类和放大器Type.GetType()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一个益智游戏,我有一个泛型类

Bit of a puzzler, I have a generic class

public abstract class MyClass<T> : UserControl
{

}

我有一个类型是这样的

Type type = Type.GetType("Type From DB as String", true, true);

我想用类型创建MyClass的实例...但这不起作用。

and I want to create and instance of MyClass using the type... But this doesn't work.

MyClass<type> control = (MyClass<type>)LoadControl("/UsercControl.ascx");

任何想法????

推荐答案

类似于这样的内容:

Something like this:

Type typeArgument = Type.GetType("Type From DB as String", true, true);
Type template = typeof(MyClass<>);
Type genericType = template.MakeGenericType(typeArgument);
object instance = Activator.CreateInstance(genericType);

现在您无法将 用作 MyClass< T> ,因为你不知道 T ...但你可以用一些不需要 T 的方法定义一个非泛型的基类或接口,然后转换为该类型。或者你可以通过反射来调用它的方法。

Now you won't be able to use that as a MyClass<T> in terms of calling methods on it, because you don't know the T... but you could define a non-generic base class or interface with some methods in which don't require T, and cast to that. Or you could call the methods on it via reflection.

这篇关于通用类和放大器Type.GetType()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-21 10:57