泛型类的默认构造函数的语法是什么?

时间:2022-04-30 22:29:15

Is it forbidden in C# to implement a default constructor for a generic class?

在c#中是否禁止为泛型类实现默认构造函数?

If not, why the code below does not compile? (When I remove <T> it compiles though)

如果没有,为什么下面的代码不编译?(当我删除 时,它会编译)

What is the correct way of defining a default constructor for a generic class then?

定义泛型类的默认构造函数的正确方法是什么?

public class Cell<T> 
{
    public Cell<T>()
    {
    }
}

Compile Time Error: Error 1 Invalid token '(' in class, struct, or interface member declaration

编译时间错误:错误1无效的令牌'('在类、结构或接口成员声明中

3 个解决方案

#1


114  

You don't provide the type parameter in the constructor. This is how you should do it.

在构造函数中不提供类型参数。你应该这样做。

public class Cell<T> 
{
    public Cell()
    {
    }
}

#2


4  

And if you need the Type as a property:

如果您需要该类型作为属性:

public class Cell<T>
{
    public Cell()
    {
        TheType = typeof(T);
    }

    public Type TheType { get;}
}

#3


0  

And if you need to inject an instance of the type:

如果需要注入类型的实例:

public class Cell<T>
{
    public T Thing { get; }

    public Cell(T thing)
    {
        Thing = thing;
    }
}

#1


114  

You don't provide the type parameter in the constructor. This is how you should do it.

在构造函数中不提供类型参数。你应该这样做。

public class Cell<T> 
{
    public Cell()
    {
    }
}

#2


4  

And if you need the Type as a property:

如果您需要该类型作为属性:

public class Cell<T>
{
    public Cell()
    {
        TheType = typeof(T);
    }

    public Type TheType { get;}
}

#3


0  

And if you need to inject an instance of the type:

如果需要注入类型的实例:

public class Cell<T>
{
    public T Thing { get; }

    public Cell(T thing)
    {
        Thing = thing;
    }
}