C#中default关键字的用途是什么?


Answers:


100

default关键字的上下文,因为它具有多种用途。我猜想您指的是其较新的C#2,即它返回类型的默认值。对于引用类型,这是null一个值,对于值类型,这是一个全为零的新实例。

这里有一些例子来说明我的意思:

using System;

class Example
{
    static void Main()
    {
        Console.WriteLine(default(Int32)); // Prints "0"
        Console.WriteLine(default(Boolean)); // Prints "False"
        Console.WriteLine(default(String)); // Prints nothing (because it is null)
    }
}


33

最常见的用法是泛型; 尽管它适用于“常规”类型(例如,default(string)等等),但这在手写代码中并不常见。

但是,我确实在执行代码生成时使用了这种方法,因为这意味着我不需要对所有不同的默认值进行硬编码-我只需找出类型并default(TypeName)在生成的代码中使用即可。

在泛型中,经典用法是TryGetValue模式:

public static bool TryGetValue(string key, out T value) {
    if(canFindIt) {
        value = ...;
        return true;
    }
    value = default(T);
    return false;
}

在这里,我们必须分配一个值以退出该方法,但是调用者实际上不必关心它是什么。您可以将此与构造函数约束进行对比:

public static T CreateAndInit<T>() where T : ISomeInterface, new() {
    T t = new T();
    t.SomeMethodOnInterface();
    return t;
}

1
+1代表T:new()与default(T)。我更喜欢T:new(),因为它调用了泛型类的完整构造函数。但是当不能满足new()约束时,default(T)极为有用。即不可变/单子不允许new()。
罗伯特·J·古德


4

“ default”关键字(除了switch-case之外)可帮助您初始化对象的实例,如类,列表和更多类型。由于其通用属性,可在您不知道对象的默认类型时为其指定默认值,因此使用它值作为避免进一步(将来)代码出错的高级方法。


0

呼应并强调它在泛型中的使用,除了代码生成外,别无其他。

如果您必须初始化为默认值(我的书中已经可疑有臭味),请弄清楚。去做就对了。

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.