【发布时间】:2012-05-02 22:17:03
【问题描述】:
可能重复:
Conditional operator assignment with Nullable<value> types?
为什么当我的函数返回一个可为空的整数“int?”时,条件运算符“?:”在这里不起作用? “return null” 有效,但对于“?:”,我必须先将“null”转换为“(int?)”。
public int? IsLongName(string name) {
int length = name.Length;
// this works without problems
if (name.Length > 10) {
return null;
} else {
return name.Length;
}
// this reports:
// Type of conditional expression cannot be determined because
// there is no implicit conversion between '<null>' and 'int'
return name.Length > 10 ? null : name.Length;
}
【问题讨论】:
-
我们没有更好的副本吗?还是在 eric 的博客上?我当然记得这个问题的答案比 jon 链接的答案更好。
-
查看 Eric Lippert 的相关博文:Type inference woes, part one
标签: c#