如何初始化泛型参数类型T?初始化、参数、类型

2023-09-03 07:55:38 作者:流泪哭到遗忘

简单问题: 如果你有一个字符串x ,初始化它,你简单的执行下列操作之一:

Simple question: If you have a string x, to initialize it you simple do one of the following:

string x = String.Empty;  

string x = null;

那么通用参数T?

What about Generic parameter T?

我试着这样做的:

void someMethod<T>(T y)
{
    T x = new T();  
    ...
}

生成错误: 无法创建变量类型T的一个实例,因为它不具备new()约束

Generate error : Cannot create an instance of the variable type 'T' because it does not have the new() constraint

推荐答案

您有两种选择:

您可以限制T:你这样做,加入:其中T:新的()你的方法。现在,你只能使用的someMethod 与具有无参数,默认的构造类型(见的