如何在C#中使用泛型类型参数作为常规类型?

问题描述:

我有一个包含一些业务对象的通用业务对象的集合类:如何在C#中使用泛型类型参数作为常规类型?

public abstract class BusinessObjectCollection<T> : ICollection<T> 
    where T : BusinessObject 

我想写一个返回类型T和一个返回类型的新实例化对象的方法在我的收藏类中的方法T.

在C++中,这将是您只需声明typedef value_type T;并使用BusinessObjectCollection :: value_type的地方,但我无法在C#中找到等效项。

有什么建议吗?

编辑:一位接近平行,我想的类型定义是方法:

Type GetGenericParameter() { 
    return typeof(T); 
} 

尝试是这样的:

public abstract class BusinessObjectCollection<T> : ICollection<T> 
    where T : BusinessObject, new() 
{ 
    // Here is a method that returns an instance 
    // of type "T" 
    public T GetT() 
    { 
     // And as long as you have the "new()" constraint above 
     // the compiler will allow you to create instances of 
     // "T" like this 
     return new T(); 
    } 
} 

在C#中,你可以使用类型参数(即T ),就像你在代码中的任何其他类型一样 - 没有什么额外的你需要做的。

为了能够创建T(不使用反射)的实例,您必须使用new()约束类型参数,这将保证任何类型参数包含无参数构造函数。

+0

其实这也使用反射。 C#发出对Activator.CreateInstance的调用。 – Josh 2010-02-24 22:54:47

+0

*编译器*发出对“Activator.CreateInstance”的调用是非常正确的。我只是简单地说,OP不必直接使用反射API,并不是说反射在封面下不被使用。 – 2010-02-25 00:34:47

至于找到一个类型:

如果你需要知道什么T的类型,you can simply use typeof(T)