什么是默认(对象); 做C#?

Nib*_*Pig 123 c#

谷歌搜索只提出关键字,但我偶然发现了一些代码

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)

  • @The Machine Charmer:不.你不能超载`default`. (3认同)
  • 如果我使用属性 `int n` 创建 `class Foo`。我可以“重载”`default` 以将`n` 设置为`5` 而不是`0`? (2认同)

Pra*_*are 13

default关键字将返回null引用类型和zero数值类型.

对于structs,它将返回初始化为struct或null的结构的每个成员,具体取决于它们是值还是引用类型.

来自MSDN

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)


rah*_*hul 6

指定类型参数的默认值。对于引用类型,该值将为 null;对于值类型,该值为零。

查看默认值


ken*_*ytm 5

默认值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)