为什么我不能投一个int为字符串,这个三元操作中 [英] Why can't I cast an int to a string within this ternary operation

查看:122
本文介绍了为什么我不能投一个int为字符串,这个三元操作中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我留下了一些代码为简洁起见...

I left some code out for brevity...

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

ddlCategory.SelectedValue = q.parentID == 0 ? 0 : id.ToString();



我得到的错误:

I get the error:

无法确定条件表达式的类型,因为有'廉政'和'串'的(它谈论的 id.ToString()之间不存在隐式转换件。)

Type of conditional expression cannot be determined because there is no implicit conversion between 'int' and 'string' (It's talking about the id.ToString() piece.)

我试过 Convert.ToString(),我试图把(串)的id ,但没有奏效。

I tried Convert.ToString() and I tried putting (string) infront of id but that didn't work.

推荐答案

由于三元的两个返回的值是相同类型的不 - 一个是 INT ,另一个是字符串。编译器不能推导出三元表达式的返回类型是什么

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.

这篇关于为什么我不能投一个int为字符串,这个三元操作中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆