Why can't I cast an int to a string within this ternary operation

前端 未结 2 1958
梦如初夏
梦如初夏 2021-01-24 04:57

I left some code out for brevity...

int id = Convert.ToInt32(Page.RouteData.Values[\"id\"]);
var q = db.Categories.SingleOrDefault(x => x.categoryID == id);

         


        
相关标签:
2条回答
  • 2021-01-24 05:16

    Because your are trying to make the ternary operator evaluate to either an int (0) or a string (id.ToString()). Replace the 0 with "0".

    0 讨论(0)
  • 2021-01-24 05:28

    Because the two return values of the ternary are not of the same type -- one is int and the other is string. The compiler cannot deduce what the ternary expression's return type is.

    Solution: Return the same type from both branches, or cast one of them to a base of the other. object will do fine.

    0 讨论(0)
提交回复
热议问题