C# struct new StructType() 与默认值(StructType) [英] C# struct new StructType() vs default(StructType)

查看:42
本文介绍了C# struct new StructType() 与默认值(StructType)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有一个结构

public struct Foo
{
    ...
}

Foo foo = new Foo();

Foo foo = default(Foo);

?

推荐答案

您可能想知道,如果它们完全相同,为什么有两种方法可以做同样的事情.

You might wonder why, if they are exactly the same, there are two ways to do the same thing.

它们并不完全相同,因为每个引用类型或值类型都保证具有默认值但并非每个引用类型都保证具有无参数构造函数:

They are not quite the same because every reference type or value type is guaranteed to have a default value but not every reference type is guaranteed to have a parameterless constructor:

static T MakeDefault<T>()
{
    return default(T); // legal
    // return new T(); // illegal
}

这篇关于C# struct new StructType() 与默认值(StructType)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆