如何初始化泛型参数类型T? [英] How to initialize generic parameter type T?
问题描述
简单问题:
如果你有一个字符串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
与具有无参数,默认的构造类型(见的Constraints 的)。
You can constrain T: you do this by adding: where T : new()
to your method. Now you can only use the someMethod
with a type that has a parameterless, default constructor (see Constraints on Type Parameters).
您也可以使用默认(T)
。对于引用类型,这会给空
。但是,例如,对于一个整数值,这会给 0
(见的默认关键字的通用code )。
Or you use default(T)
. For a reference type, this will give null
. But for example, for an integer value this will give 0
(see default Keyword in Generic Code).
下面是一个演示的差异的基本控制台应用程序:
Here is a basic console application that demonstrates the difference:
using System;
namespace Stackoverflow
{
class Program
{
public static T SomeNewMethod<T>()
where T : new()
{
return new T();
}
public static T SomeDefaultMethod<T>()
where T : new()
{
return default(T);
}
struct MyStruct { }
class MyClass { }
static void Main(string[] args)
{
RunWithNew();
RunWithDefault();
}
private static void RunWithDefault()
{
MyStruct s = SomeDefaultMethod<MyStruct>();
MyClass c = SomeDefaultMethod<MyClass>();
int i = SomeDefaultMethod<int>();
bool b = SomeDefaultMethod<bool>();
Console.WriteLine("Default");
Output(s, c, i, b);
}
private static void RunWithNew()
{
MyStruct s = SomeNewMethod<MyStruct>();
MyClass c = SomeNewMethod<MyClass>();
int i = SomeNewMethod<int>();
bool b = SomeNewMethod<bool>();
Console.WriteLine("New");
Output(s, c, i, b);
}
private static void Output(MyStruct s, MyClass c, int i, bool b)
{
Console.WriteLine("s: " + s);
Console.WriteLine("c: " + c);
Console.WriteLine("i: " + i);
Console.WriteLine("b: " + b);
}
}
}
这将产生以下输出:
It produces the following output:
New
s: Stackoverflow.Program+MyStruct
c: Stackoverflow.Program+MyClass
i: 0
b: False
Default
s: Stackoverflow.Program+MyStruct
c:
i: 0
b: False
这篇关于如何初始化泛型参数类型T?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!