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

如何在C#中作为常规类型访问和使用泛型类型参数?,c#,generics,type-parameter,C#,Generics,Type Parameter,我有一个通用业务对象集合类,其中包含一些业务对象: public abstract class BusinessObjectCollection<T> : ICollection<T> where T : BusinessObject 试着这样做: public abstract class BusinessObjectCollection<T> : ICollection<T> where T : BusinessObjec

我有一个通用业务对象集合类,其中包含一些业务对象:

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

试着这样做:

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();
    }
}
公共抽象类BusinessObjectCollection:ICollection
其中T:BusinessObject,new()
{
//下面是一个返回实例的方法
//类型为“T”
公共T GetT()
{
//只要你有上面的“new()”约束
//编译器将允许您创建
//像这样的“T”
返回新的T();
}
}
在C#中,您可以像在代码中使用任何其他类型一样使用类型参数(即
T
),无需执行任何额外操作


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

关于查找类型:


如果您需要知道T的类型,实际上它也使用反射。C#发出对Activator.CreateInstance的调用。编译器发出对
Activator.CreateInstance
的调用是正确的。我只是简单地说OP不必直接使用反射API,而不是说反射根本没有在封面下使用。
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();
    }
}