Ответ 1
У вас есть два варианта:
Вы можете ограничить T: вы делаете это, добавляя: where T : new()
к вашему методу. Теперь вы можете использовать только someMethod
с типом, который имеет конструктор по умолчанию без параметров (см. Ограничения по параметрам типа).
Или вы используете default(T)
. Для ссылочного типа это даст null
. Но, например, для целочисленного значения это даст 0
(см. ключевое слово по умолчанию в Generic Code).
Вот базовое консольное приложение, которое демонстрирует разницу:
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);
}
}
}
Он производит следующий вывод:
New
s: Stackoverflow.Program+MyStruct
c: Stackoverflow.Program+MyClass
i: 0
b: False
Default
s: Stackoverflow.Program+MyStruct
c:
i: 0
b: False