【发布时间】:2023-03-23 06:05:02
【问题描述】:
考虑
interface IResult {}
class Result : IResult {}
class Results : IResult {}
class Producer {
private Results results;
IResult DoSomething() {
return results ?? new Result();
}
}
编译器错误导致失败
Operator '??' cannot be applied to operands of type `Result` and `Results`
对我来说,这是出乎意料的行为。考虑一下,.NET 框架可能会创建一个Results 类型的中间变量(左操作数)。右操作数Result 的类型不同,因此会产生类型转换错误。这个假设正确吗?
如果是,为什么 csc 不会检测到中间变量是 IResult 类型的?
所以我把代码改成如下样子
return results == null ? new Result() : results;
但是这段代码出错了
There is no explicit conversion between `Result` and `Results`
为什么?我不希望这样,因为这两个实例都符合 IResult。
【问题讨论】:
-
左操作数的类型是
Results,而不是IResult。您需要强制转换才能让编译器理解这一点。
标签: c# .net compiler-errors polymorphism operators