对具有动态操作数的空合并运算符进行类型检查
Type checks for null-coalescing operator with dynamic operand
考虑以下最小示例:
class Program {
static void Main(string[] args) {
Dictionary<string, int> obj = GetDynamic() ?? new List<string>();
}
private static dynamic GetDynamic() {
return null;
}
}
代码将编译,但在运行时失败,因为 List<T>
无法转换为 Dictionary<TKey, TValue>
。我猜这是因为表达式 GetDynamic() ?? new List<string>()
在编译时解析为类型 dynamic
。
当空合并运算符的任一操作数与预期的 return 类型不匹配时,是否有办法强制产生编译错误?
Why the compiler can't tell something's wrong here (as it's pretty obvious for a developer).
因为编写代码的开发人员明确告诉编译器不要检查。当我们使用 dynamic
时,我们实际上是在告诉编译器关闭静态类型检查。
以这种方式使用 dynamic
并不是一个好的设计。如果您不知道返回的类型,那么代码设计就有缺陷,当它 returns 除了 Dictionary<string, int>
之外的任何其他类型时,您仍然会收到运行时错误。将 dynamic
更改为 Dictionary<string, int>
,您将根据需要得到 compile-time 错误。
这可能会回答您的问题,但这绝不是一件好事。如果你转换 dynamic
,你会得到编译器错误:
Dictionary<string, int> obj = (Dictionary<string, int>)GetDynamic() ?? new Dictionary<string, int>();
考虑以下最小示例:
class Program {
static void Main(string[] args) {
Dictionary<string, int> obj = GetDynamic() ?? new List<string>();
}
private static dynamic GetDynamic() {
return null;
}
}
代码将编译,但在运行时失败,因为 List<T>
无法转换为 Dictionary<TKey, TValue>
。我猜这是因为表达式 GetDynamic() ?? new List<string>()
在编译时解析为类型 dynamic
。
当空合并运算符的任一操作数与预期的 return 类型不匹配时,是否有办法强制产生编译错误?
Why the compiler can't tell something's wrong here (as it's pretty obvious for a developer).
因为编写代码的开发人员明确告诉编译器不要检查。当我们使用 dynamic
时,我们实际上是在告诉编译器关闭静态类型检查。
以这种方式使用 dynamic
并不是一个好的设计。如果您不知道返回的类型,那么代码设计就有缺陷,当它 returns 除了 Dictionary<string, int>
之外的任何其他类型时,您仍然会收到运行时错误。将 dynamic
更改为 Dictionary<string, int>
,您将根据需要得到 compile-time 错误。
这可能会回答您的问题,但这绝不是一件好事。如果你转换 dynamic
,你会得到编译器错误:
Dictionary<string, int> obj = (Dictionary<string, int>)GetDynamic() ?? new Dictionary<string, int>();