相关疑难解决方法(0)

可空类型和三元运算符:为什么是`?10:null`禁止?

我刚刚遇到一个奇怪的错误:

private bool GetBoolValue()
{
    //Do some logic and return true or false
}
Run Code Online (Sandbox Code Playgroud)

然后,在另一种方法中,这样的事情:

int? x = GetBoolValue() ? 10 : null;
Run Code Online (Sandbox Code Playgroud)

很简单,如果方法返回true,则为Nullable intx 赋值10 .否则,将null赋给nullable int.但是,编译器抱怨:

错误1无法确定条件表达式的类型,因为int和之间没有隐式转换<null>.

我疯了吗?

.net c# nullable conditional-operator

242
推荐指数
6
解决办法
7万
查看次数

条件运算符不能隐式转换?

我对这个小C#quirk感到有点难过:

给定变量:

Boolean aBoolValue;
Byte aByteValue;
Run Code Online (Sandbox Code Playgroud)

以下编译:

if (aBoolValue) 
    aByteValue = 1; 
else 
    aByteValue = 0;
Run Code Online (Sandbox Code Playgroud)

但这不会:

aByteValue = aBoolValue ? 1 : 0;
Run Code Online (Sandbox Code Playgroud)

错误说:"不能隐式地将类型'int'转换为'byte'."

当然,这个怪物会编译:

aByteValue = aBoolValue ? (byte)1 : (byte)0;
Run Code Online (Sandbox Code Playgroud)

这里发生了什么?

编辑:

使用VS2008,C#3.5

c# types conditional-operator implicit-cast

61
推荐指数
3
解决办法
4797
查看次数

三元条件下的隐式转换问题

可能重复:
条件运算符无法隐式转换?
为什么null需要显式类型转换?

我有一个搜索,并没有找到一个很好的解释为什么发生以下情况.
我有两个具有共同接口的类,我尝试使用三元运算符初始化此接口类型的实例,如下所示但是无法编译错误"无法确定条件表达式的类型,因为之间没有隐式转换'xxx.Class1'和'xxx.Class2':

public ConsoleLogger : ILogger  { .... }

public SuppressLogger : ILogger  { .... }

static void Main(string[] args)
{
   .....
   // The following creates the compile error
   ILogger logger = suppressLogging ? new SuppressLogger() : new ConsoleLogger();
}
Run Code Online (Sandbox Code Playgroud)

如果我明确地将第一个conditioin强制转换为我的界面,这是有效的:

   ILogger logger = suppressLogging ? ((ILogger)new SuppressLogger()) : new ConsoleLogger();
Run Code Online (Sandbox Code Playgroud)

显然我总能做到这一点:

   ILogger logger;
   if (suppressLogging)
   {
       logger = new SuppressLogger();
   }
   else
   {
       logger = new ConsoleLogger();
   }
Run Code Online (Sandbox Code Playgroud)

替代方案很好,但我不能完全理解为什么第一个选项因隐式转换错误而失败,因为在我看来,这两个类都是ILogger类型,我不是真的想要进行转换(隐式或显式) ).我敢肯定这可能是一个静态语言编译问题,但我想了解发生了什么.

c# compiler-errors implicit-conversion

21
推荐指数
2
解决办法
3139
查看次数