据我了解默认值(对象),其中'对象'是任何引用类型始终返回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(); }更多推荐
指定引用类型的默认值
发布评论