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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13989093/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 10:17:04  来源:igfitidea点击:

How to initialize generic parameter type T?

c#.netgenerics

提问by JavaSa

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

简单的问题:
如果您有一个string x, 初始化它,您只需执行以下操作之一:

string x = String.Empty;  

or

或者

string x = null;

What about Generic parameter T?

通用参数 T 怎么样?

I've tried doing:

我试过这样做:

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

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

生成错误:
无法创建变量类型“T”的实例,因为它没有 new() 约束

采纳答案by Wouter de Kort

You have two options:

您有两个选择:

You can constrain T: you do this by adding: where T : new()to your method. Now you can only use the someMethodwith a type that has a parameterless, default constructor (see Constraints on Type Parameters).

您可以通过where T : new()在方法中添加:来约束 T: 您可以做到这一点。现在,您只能将someMethod与具有无参数默认构造函数的类型一起使用(请参阅类型参数的约束)。

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).

或者你使用default(T). 对于引用类型,这将给出null. 但是例如,对于整数值,这将给出0(请参阅通用代码中的默认关键字)。

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

回答by Habib

use defaultkeyword.

使用default关键字。

T x = default(T);

See: default Keyword in Generic Code (C# Programming Guide)

请参阅:通用代码中的默认关键字(C# 编程指南)

Given a variable t of a parameterized type T, the statement t = null is only valid if T is a reference type and t = 0 will only work for numeric value types but not for structs. The solution is to use the default keyword, which will return null for reference types and zero for numeric value types. For structs, it will return each member of the struct initialized to zero or null depending on whether they are value or reference types.

给定参数化类型 T 的变量 t,语句 t = null 仅在 T 是引用类型时才有效,并且 t = 0 仅适用于数值类型而不适用于结构。解决方案是使用 default 关键字,它将为引用类型返回 null,为数值类型返回零。对于结构,它将返回结构的每个成员初始化为零或空值,具体取决于它们是值类型还是引用类型。

回答by Lee

You need to add a newconstraint for the type parameter T.

您需要new为类型参数添加约束T

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

This will only be valid for types with a default constructor however.

但是,这仅对具有默认构造函数的类型有效。

The whereclause for Tis a generic type constraint. In this case, it requires that any type Tthis method is applied to must have a public parameterless constructor.

wherefor子句T是一个泛型类型约束。在这种情况下,它要求T应用此方法的任何类型都必须具有公共无参数构造函数。

回答by Amar

You may use defaultconstruct to set it to whatever that Type's default is.

您可以使用defaultconstruct 将其设置为Type 的默认值。

The default keyword allows you to tell the compiler that at compile time the default value of this variable should be used. If the type argument supplied is a numeric value (e.g., int, long, decimal), then the default value is zero. If the type argument supplied is a reference type, then the default value is null. If the type argument supplied is a struct, then the default value of the struct is determined by initializing each member field of the struct to zero for numeric types or null for reference types.

default 关键字允许您告诉编译器在编译时应使用此变量的默认值。如果提供的类型参数是数字值(例如,int、long、decimal),则默认值为零。如果提供的类型参数是引用类型,则默认值为 null。如果提供的类型参数是结构体,则结构体的默认值是通过将结构体的每个成员字段初始化为零(对于数字类型)或 null(对于引用类型)来确定的。

Use something like :

使用类似的东西:

T data = default(T);

T data = default(T);

For details, read : Initializing Generic Variables to Their Default Values

有关详细信息,请阅读:将通用变量初始化为其默认值

回答by Oscar

If you really need an instance of T and not a default null value for reference types, use:

如果您确实需要 T 的实例而不是引用类型的默认空值,请使用:

Activator.CreateInstance()