本文介绍了c#三元运算符返回不同类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图使用三元组返回不同类型,虽然我似乎遇到一些问题。我的问题是三元运算符不能返回不同类型?
//这行会导致错误
propertyGrid.Instance =(directoryRecord.directoryInfo!= null)
? directoryRecord.directoryInfo
:directoryRecord.fileInfo;
//编译精细
propertyGrid.Instance = directoryRecord.directoryInfo;
//编译精细
propertyGrid.Instance = directoryRecord.fileInfo;
错误
解决方案
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;
这篇关于c#三元运算符返回不同类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!