我对这个小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
可能重复:
条件运算符无法隐式转换?
为什么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类型,我不是真的想要进行转换(隐式或显式) ).我敢肯定这可能是一个静态语言编译问题,但我想了解发生了什么.
我班上有以下内容:
public bool? EitherObject1OrObject2Exists => ((Object1 != null || Object2 != null) && !(Object1 != null && Object2 != null)) ? true : null;
Run Code Online (Sandbox Code Playgroud)
但是在Visual Studio中,我收到一个IntelliSense错误,即使该字段可以为空,也不能在"bool"和"NULL"之间进行转换.我做错了什么?有没有更清晰的方法来检查两个对象中的任何一个是否为空,但其中一个必须为空?