指定引用类型的默认值 [英] Specify default value for a reference type

查看:176
本文介绍了指定引用类型的默认值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

据我了解默认值(对象),其中'对象'是任何引用类型始终返回null,但我可以指定默认的是什么?举例来说,我想默认的(对象)==新的对象();

As I understand default(object) where 'object' is any reference type always returns null, but can I specify what a default is? For instance, I want default(object) == new object();

推荐答案

没有。 默认(类型)总是返回同样的事情 - 该类型的zero'ed去的版本。对于引用类型,这是一个句柄总是与零值设置对象 - 这相当于。对于一个值类型,这始终设置为零所有成员的结构

No. default(type) will always return the same thing - a "zero'ed out" version of that type. For a reference type, this is a handle to an object that is always set with a value of zero - which equates to null. For a value type, this is always the struct with all members set to zero.

有没有办法覆盖这种行为 - 语言规范的目的是这样

There is no way to override this behavior - the language specification is designed this way.

编辑:您的评论:

只是为了能够说 FirstOrDefault(),从来没有得到一个空。

Just to be able to say FirstOrDefault() and never get a null.

我不会在任何情况下,推荐这个。用户期望 FirstOrDefault()返回失败。这将是更好编写自己的扩展方法:

I would not recommend this in any case. Users expect FirstOrDefault() to return null on failure. It would be better to write your own extension method:

static T FirstOrNewInstance<T>(this IEnumerable<T> sequence) where T : class, new()
{
     return sequence.FirstOrDefault() ?? new T();
} 

这篇关于指定引用类型的默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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