2013-10-06 37 views
1

我正在尝试检查我的对象信息是否是word.Selection或word.Document,然后在我的程序中稍后使用它。使用条件运算符投射到不同类型

这里是我遇到一些麻烦。

object info; 
var doc = info is word.Document ? info as word.Document : info as word.Selection; 
//do something with doc.Words; 

它返回此错误:

Type of conditional expression cannot be determined because there is no implicit conversion between 'Microsoft.Office.Interop.Word.Document' and 'Microsoft.Office.Interop.Word.Selection'

我似乎无法避开这个错误

+0

一般来说,使用'is'运算符,然后使用'as'运算符或铸造是一种代码味道 - 如果您想尝试投射,尝试投射,这个'is'运算符在您* *实际上不想投。 –

回答

3

当您使用?:操作的两个结果必须是同一类型的。

如果情况使用标准:

if(info is word.Document) 
{ 
    //your code 
} 
else 
{ 
} 
+0

是否有任何其他方式可以用于处理word.Document或word.Selection? 使用if语句会使我的代码翻倍。 – ismellike

+2

@ismellike:试试这个'var doc = info as word.Document?信息作为词。选择'。如果转换失败,'as'转换将返回'null',如果前一个值为'null',则空合并运算符将执行第二个部分。 –

+0

@JeroenVannevel +1不错的一个。你有没有想过写一个答案?这可能是OP正在寻找的那个。 –

2

?: Operator (C# Reference)

Either the type of first_expression and second_expression must be the same, or an implicit conversion must exist from one type to the other.

在你的第一个表达式返回word.Document,但第二次返回word.Selection。既然他们不一样,但看起来他们之间并没有隐含的对话。

相关问题