谷歌搜索只提出关键字,但我偶然发现了一些代码
MyVariable = default(MyObject);
Run Code Online (Sandbox Code Playgroud)
我想知道这是什么意思......
Mar*_*ell 177
null
Nullable<T>
,返回零初始化值Nullable<T>
它返回空(伪null)值(实际上,这是第二个项目符号的重新声明,但值得将其显式化)最常用的default(T)
是泛型,以及Try...
模式之类的东西:
bool TryGetValue(out T value) {
if(NoDataIsAvailable) {
value = default(T); // because I have to set it to *something*
return false;
}
value = GetData();
return true;
}
Run Code Online (Sandbox Code Playgroud)
碰巧的是,我也在一些代码生成中使用它,初始化字段/变量很痛苦 - 但是如果你知道类型:
bool someField = default(bool);
int someOtherField = default(int)
global::My.Namespace.SomeType another = default(global::My.Namespace.SomeType);
Run Code Online (Sandbox Code Playgroud)
Pra*_*are 13
default
关键字将返回null
引用类型和zero
数值类型.
对于struct
s,它将返回初始化为struct或null的结构的每个成员,具体取决于它们是值还是引用类型.
Simple Sample code :<br>
class Foo
{
public string Bar { get; set; }
}
struct Bar
{
public int FooBar { get; set; }
public Foo BarFoo { get; set; }
}
public class AddPrinterConnection
{
public static void Main()
{
int n = default(int);
Foo f = default(Foo);
Bar b = default(Bar);
Console.WriteLine(n);
if (f == null) Console.WriteLine("f is null");
Console.WriteLine("b.FooBar = {0}",b.FooBar);
if (b.BarFoo == null) Console.WriteLine("b.BarFoo is null");
}
}
Run Code Online (Sandbox Code Playgroud)
OUTPUT:
0
f is null
b.FooBar = 0
b.BarFoo is null
Run Code Online (Sandbox Code Playgroud)
默认值MyObject
. 请参阅通用代码(C# 编程指南) (MSDN)中的默认关键字:
在泛型类和方法中,出现的一个问题是,当您事先不知道以下内容时,如何为参数化类型 T 分配默认值:
- T 是引用类型还是值类型。
- 如果 T 是值类型,则它是数值还是结构。
给定参数化类型 T 的变量 t,仅当 T 是引用类型时,语句 t = null 才有效,并且 t = 0 仅适用于数值类型,不适用于结构。解决方案是使用 default 关键字,该关键字对于引用类型将返回 null,对于数值类型将返回零。对于结构体,它将返回初始化为零或 null 的结构体的每个成员,具体取决于它们是值类型还是引用类型。GenericList 类中的以下示例显示了如何使用 default 关键字。有关更多信息,请参阅泛型概述。
public class GenericList<T>
{
private class Node
{
//...
public Node Next;
public T Data;
}
private Node head;
//...
public T GetNext()
{
T temp = default(T);
Node current = head;
if (current != null)
{
temp = current.Data;
current = current.Next;
}
return temp;
}
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
77070 次 |
最近记录: |