三元语句内联如果不编译

时间:2014-03-31 20:08:57

标签: c# ternary-operator

我正在尝试运行此内联if语句

pRun.StartInfo.FileName = File.Exists("C:\\Test\\Data\\TestingPurposes\\" + UserName 
+ "DailyInfo") ? pRun.StartInfo.UseShellExecute = true : MessageBox.Show("Please 
verify that this file exists");

但是我收到了编译错误:

  

无法确定条件表达式的类型,因为'bool'和'System.Windows.Forms.DialogResult'之间没有隐式转换

如何删除此错误并运行以下语句?我想要做的是检查文件是否存在,如果存在,打开它。如果没有,则生成带有所述消息的messagebox

1 个答案:

答案 0 :(得分:4)

为了使用三元运算符,两个语句都应该返回相同的类型,或者一个类型应该可以转换为其他类型。参见documentation

  

first_expression和second_expression的类型必须相同,或者从一种类型到另一种类型必须存在隐式转换。

你需要使用简单的if语句intead,它也更可读

if(File.Exists("C:\\Test\\Data\\TestingPurposes\\" + UserName + "DailyInfo"))
{ 
   pRun.StartInfo.UseShellExecute = true   
}
else MessageBox.Show("Please verify that this file exists");