c# Ternary operator returning different types

我是研究僧i 提交于 2019-12-12 10:34:24

问题


I'm trying to use the ternary to return differing types, although I seem to be encountering some problems. My question is can the ternary operator not return differing types?

// This line causes an error
propertyGrid.Instance = (directoryRecord.directoryInfo != null) 
    ? directoryRecord.directoryInfo 
    : directoryRecord.fileInfo;

// Compiles fine
propertyGrid.Instance = directoryRecord.directoryInfo;

// Compiles fine
propertyGrid.Instance = directoryRecord.fileInfo;

Error

Type of conditional expression cannot be determined because there is no implicit conversion between 'System.IO.DirectoryInfo' and 'System.IO.FileInfo'


回答1:


No, this doesn't work like that.
The expression of a conditional operator has a specific type. Both types used in the expression must be of the same type or implicitly convertible to each other.

You can make it work like this:

propertyGrid.Instance = (directoryRecord.directoryInfo != null) 
    ? (object)directoryRecord.directoryInfo 
    : (object)directoryRecord.fileInfo;



回答2:


No.
Both return values ultimately need to be stored in the same single variable that will hold the result.
So the compiler has to have a way of deciding the type of that variable / storage area.
Because of the language type safety you have to know the type, and they are both gonna end up in the same variable.



来源:https://stackoverflow.com/questions/12894911/c-sharp-ternary-operator-returning-different-types

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!