C#中泛型类型的默认值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/370001/
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-04 00:49:16  来源:igfitidea点击:

default value for generic type in c#

c#genericsdefault-value

提问by BCS

The docs for Dictionary.TryGetValuesay:

Dictionary.TryGetValue的文档说:

When this method returns, [the value argument] contains the value associated with the specified key, if the key is found; otherwise, the default value for the type of the value parameter. This parameter is passed uninitialized.

当此方法返回时,[value 参数] 包含与指定键关联的值(如果找到了键);否则,为 value 参数类型默认值。此参数未初始化传递。

I need to mimic this in my class. How do I find the default value for type T?

我需要在我的课堂上模仿这一点。如何找到类型 T 的默认值?



How can this question be modified to make it show up in the search?

如何修改此问题以使其显示在搜索中?

Exact duplicate of Returning a default value. (C#)

返回默认值的完全重复。(C#)

采纳答案by Nathan W

You are looking for this:

你正在寻找这个:

default(T);

so:

所以:

public T Foo<T>(T Bar)
{
   return default(T);
}

回答by Szymon Rozga

default(T);

回答by Darin Dimitrov

Using the defaultkeyword:

使用默认关键字:

T t = default(T)