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

问题描述 投票:115回答:8

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

MyVariable = default(MyObject);

我想知道这是什么意思......

c#
8个回答
167
投票
  • 对于reference-type,它返回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;
}

碰巧的是,我也在一些代码生成中使用它,初始化字段/变量很痛苦 - 但是如果你知道类型:

bool someField = default(bool);
int someOtherField = default(int)
global::My.Namespace.SomeType another = default(global::My.Namespace.SomeType);

13
投票

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

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

from 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");

        }
    }

OUTPUT:

0
f is null
b.FooBar = 0
b.BarFoo is null

3
投票

MyObject的默认值。请参阅default Keyword in Generic Code (C# Programming Guide)(MSDN):

在泛型类和方法中,出现的一个问题是,如果您事先不知道以下内容,如何为参数化类型T分配默认值:

  • T是引用类型还是值类型。
  • 如果T是值类型,则它是数值还是结构。

给定参数化类型T的变量t,语句t = null仅在T是引用类型时有效,并且t = 0仅适用于数值类型而不适用于结构。解决方案是使用default关键字,它将为引用类型返回null,为数值类型返回零。对于结构体,它将返回初始化为struct或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;
    }
}

2
投票

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

default


1
投票

default关键字返回所请求类型的变量的“默认”或“空”值。

对于所有参考类型(使用classdelegate等定义),这是null。对于值类型(使用structenum等定义),它是一个全零值(例如,int 0DateTime 0001-01-01 00:00:00等)。

它主要用于可以应用于引用和值类型的通用代码,因为您无法将null分配给值类型变量。


0
投票

它将对象的默认值设置为变量:null表示引用类型,0表示值类型。


0
投票

如果尚未应用约束来将泛型类型参数限制为引用类型,则还可以传递值类型(如结构)。在这种情况下,将type参数与null进行比较将始终为false,因为struct可以为空,但从不为null

错误的代码

public void TestChanges<T>(T inputValue)

            try
            {
                if (inputValue==null)
                    return;
                //operation on inputValue

           }
            catch
            {
                // ignore this.
            }
        }

修正

public void TestChanges<T>(T inputValue)

            try
            {
                if (object.Equals(inputValue, default(T)) )
                    return;
                //operation on inputValue

           }
            catch
            {
                // ignore this.
            }
        }

-1
投票

也许这可以帮助你:

using System;
using System.Collections.Generic;
namespace Wrox.ProCSharp.Generics
{
    public class DocumentManager < T >
    {
        private readonly Queue < T > documentQueue = new Queue < T > ();
        public void AddDocument(T doc)
        {
            lock (this)
            {
                documentQueue.Enqueue(doc);
            }
        }

        public bool IsDocumentAvailable
        {
            get { return documentQueue.Count > 0; }
        }
    }
}

无法为泛型类型指定null。原因是泛型类型也可以实例化为值类型,并且只允许使用引用类型为null。要避免此问题,可以使用default关键字。使用default关键字,null将分配给引用类型,0将分配给值类型。

public T GetDocument()
{
    T doc = default(T);
    lock (this)
    {
        doc = documentQueue.Dequeue();
    }
    return doc;
}

default关键字具有多种含义,具体取决于使用它的上下文。 switch语句使用默认值来定义默认大小写,并且使用泛型默认用于将泛型类型初始化为null或0,具体取决于它是引用还是值类型。

© www.soinside.com 2019 - 2024. All rights reserved.