泛型类,如何设置在运行时的类型? [英] generic class, how to set the type in runtime?

查看:209
本文介绍了泛型类,如何设置在运行时的类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个泛型类,但我知道在运行时类型,而不是在设计,所以我想知道如何设置在运行时的类型。

I have created a generic class, but I know the type in runtime, not in design, so I would like to know how to set the type in runtime.

例如,我有:

public class MyGenericClass<T>
{
....
}



然后我试着使用它。我在其他类中的方法,消耗这个通用类。在这个类的构造函数,我收到的参数,我想要的类型,所以我必须在我救我需要的类型的类型属性。所以,我想这样的:

Then I try to use it. I have a method in other class, that consume this generic class. In the constructor of this class, I receive as parameter the type that I want, so I have a type property in which I save the type that I need. So I am trying this:

MyGenericClass<_typeNeeded> myClass = new MyGenericClass<typeNeeded>();



但是,这并不正常工作。

But this does not work.

我怎样才能设置在运行时的类型,我创建了一个类?

How can I set the type in runtime in a class that I created?

我使用C#4.0。

感谢。
Daimroc

Thanks. Daimroc.

编辑:我想要做的是以下几点。我有需要做一些数据库查询的类。该查询始终返回相同的信息,一类,但包含这个类来自不同表中的信息。这是因为我需要确定的是什么查询使用。要决定使用何种查询我用我收到的类型。

What I want to do is the following. I have a class that need to do some queries to the database. This queries always return the same information, a class, but the information that contains this class come from different tables. This is because I need to determinate what query to use. To decide what query to use I use the type that I receive.

是因为这个原因,我不知道设计的类型,但在运行时。

Is for this reason that I don't know in design the type, but is in runtime.

我可以使用,这将通过将实施的类的接口,并利用与正确的类实例化的接口,但是这使我有一个开关或若实例化的时刻,这是我会尽量避免,我想要的东西更通用。另外,如果我用这个解决方案,有一个如果instantion的那一刻,我可以创建通用类,所以我就只有一个班,这将是更容易维护。

I could use an interface that it would be implemented by to classes, and use the interface instantiated with the correct class, but this make me to have a switch or an if in the moment of the instantiation, and this is what I try to avoid, I want something more generic. Also, If I use this solution, to have an if in the moment of the instantion, I can create the generic class, so I would have only one class and it would be more maintainable.

推荐答案

您可以用另一种方式创建类,传递给构造要使用和利用的 动态 关键字。

You can create your class in another way, passing to the constructor the type that you want to use and exploit the dynamic keyword.

例如:

class MyGeneralClass
{
    dynamic myVariable;
    Type type;

    public MyGeneralClass(Type type)
    {  
        this.type = type;
        myVariable = Activator.CreateInstance(type);
        //And then if your type is of a class you can use its methods      
        //e.g. myVariable.MyMethod();
    }

    //If your function return something of type you can also use dynamic
    public dynamic Function()
    {
        return Activator.CreateInstance(type);
    }
}

这篇关于泛型类,如何设置在运行时的类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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