在 String.Format 中对混合数据类型使用条件运算符
Using conditional operator with mixed data types in String.Format
我有一个 String.Format 方法,我想根据是否满足条件插入字符串或整数。我的代码如下所示:
Box.Text = String.Format("{0}", ScoreBoolCheck ? student1.ScoreInt : "null");
因此理想情况下,该方法应检查 ScoreBoolCheck 是否为真,如果是,则插入 student1.ScoreInt,但如果不是,则应插入字符串 "null"。
但是,这还行不通。我收到一条警告,上面写着 "there is no implicit conversion between int and string." 有人看到我哪里出错了吗?在此先感谢您的帮助。
您需要将 int
转换为 string
:
String.Format("{0}", ScoreBoolCheck ? student1.ScoreInt.ToString() : "null");
只需转换为 object
:
Box.Text = String.Format("{0}", ScoreBoolCheck ? (object)student1.ScoreInt : "null");
因为存在从 string
到 object
的隐式转换,所以这会工作得很好。假设 ScoreInt
是一个 int
,它将被装箱,但是在将参数传递给 String.Format
时无论如何它都会被装箱(它的最后一个参数是 object[]
类型)。
需要转换,因为三元表达式必须有一个类型。
你不能写:
var x = someCondition ? 42 : Guid.NewGuid();
因为无法将类型分配给 x
,因为 int
和 Guid
不兼容(其中的 none 可以分配给另一个) .
但是如果你写:
var x = someCondition ? (object)42 : Guid.NewGuid();
那么 x
明确属于 object
类型。 Guid
可以隐式装箱到 object
。
我有一个 String.Format 方法,我想根据是否满足条件插入字符串或整数。我的代码如下所示:
Box.Text = String.Format("{0}", ScoreBoolCheck ? student1.ScoreInt : "null");
因此理想情况下,该方法应检查 ScoreBoolCheck 是否为真,如果是,则插入 student1.ScoreInt,但如果不是,则应插入字符串 "null"。
但是,这还行不通。我收到一条警告,上面写着 "there is no implicit conversion between int and string." 有人看到我哪里出错了吗?在此先感谢您的帮助。
您需要将 int
转换为 string
:
String.Format("{0}", ScoreBoolCheck ? student1.ScoreInt.ToString() : "null");
只需转换为 object
:
Box.Text = String.Format("{0}", ScoreBoolCheck ? (object)student1.ScoreInt : "null");
因为存在从 string
到 object
的隐式转换,所以这会工作得很好。假设 ScoreInt
是一个 int
,它将被装箱,但是在将参数传递给 String.Format
时无论如何它都会被装箱(它的最后一个参数是 object[]
类型)。
需要转换,因为三元表达式必须有一个类型。
你不能写:
var x = someCondition ? 42 : Guid.NewGuid();
因为无法将类型分配给 x
,因为 int
和 Guid
不兼容(其中的 none 可以分配给另一个) .
但是如果你写:
var x = someCondition ? (object)42 : Guid.NewGuid();
那么 x
明确属于 object
类型。 Guid
可以隐式装箱到 object
。