c# - 为什么 default 不适用于双括号?

标签 c#

为什么编译:

return default(T);

但这不是:

return default((T));

完整的方法是

public static T PenultimateOrDefault<T>(this IEnumerable<T> items)
{
    if (items.Count() >= 2)
        return items.ElementAt(items.Count() - 2);
    else
        return default(T);
}

default((T)) 的错误是

; expected
Invalid expression term ')'
Type expected

所以看起来解析器被双括号混淆了。

最佳答案

嗯,这不是指定语言的方式。

重要的是要了解 default 就像 typeof - 它们是运算符1,而不是方法调用。这不像类型名称是一个参数 - 它是一个操作数,操作数应该只是类型名称。

C# 5 规范的第 7.6.13 节展示了默认值表达式的构造:

default-value-expression:
default ( type )

其中 type 只是类型或类型参数的名称。您不能再像在使用通用参数或声明变量时那样在此处用括号括起来:

(string) x = ""; // Invalid
var x = new List<(string)>(); // Invalid

1 它从未在规范中指定为“默认运算符”;始终是“默认值表达式”- 但它确实在所有有意义的意义上都是一个运算符,并且它与优先级表中的其他运算符一起列出。

关于c# - 为什么 default 不适用于双括号?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21622626/

相关文章:

c# - LINQ to SQL insert-if-non-existent

c# - 错误 : the type or namespace UI doesnt exist in the namespace

c# - 如何在 C# 中重构以下代码而不终止 OOPS

c# - asp.net: 无效的回发或回调参数

c# - 无法在 Xamarin 项目的 PCL 项目中使用 fileInfo 和 fileStream

c# - 我如何开始这个过程有什么问题?

c# - 跨两个列表应用运算符的 C# 惯用方法是什么?

c# - "C# compiler as a service "的状态是什么

c# - 需要重载 operator< 和 null 检查

c# - Entity Framework (EF6)+ MySql数据库第一个模型多对多关系错误查询生成