指定引用类型的默认值

编程入门 行业动态 更新时间:2024-10-08 08:25:28
本文介绍了指定引用类型的默认值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

据我了解默认值(对象),其中'对象'是任何引用类型始终返回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(); }

更多推荐

指定引用类型的默认值

本文发布于:2023-10-16 13:58:43,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1497770.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:默认值   类型

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!