2012-04-21 82 views
4

可能重复的问题:
Conditional operator assignment with Nullable<value> types?C#条件运算符:?有可空INT

为什么条件运算符“?:”这里没有工作时,我的函数返回一个可空整数“int?”? “返回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; 
    } 
+3

为什么不返回一个布尔? – 2012-04-21 17:26:45

+0

难道我们没有更好的重复吗?还是在eric的博客上?我当然记得比这个问题更好的答案。 – CodesInChaos 2012-04-21 17:30:41

+1

检查Eric Lippert的相关博客文章:[Type inference woes,part one](http://blogs.msdn.com/ericlippert/archive/2006/05/24/type-in​​ference-woes-part-one.aspx) – CodesInChaos 2012-04-21 17:42:54

回答

5

试着改变你的最后一行是:

return name.Length > 10 ? null : (int?)name.Length; 

编译器无法理解有什么的返回类型:?运营商。它具有冲突的值 - null和int。通过将int转换为可为空,编译器可以理解返回类型是可为空的,并且null也将被接受。

1

既是一个null值和int值可以隐式转换为int?数据类型,但对自己文字的null不是由编译器知道是不是object其他任何东西,如果你不告诉它。没有共同的数据类型,objectint都可以隐式转换为,这是编译器所抱怨的。如Yorye所说,您可以将int转换为int?以让编译器执行转换;您可以将int转换为int?以使编译器执行转换;您可以将int转换为int?。或者,您可以将null转换为int?,然后允许编译为使用从intint?的隐式转换。

0

运算符?:的两个条件必须是隐式兼容的。 int永远不可能是null,所以会出现编译时错误(同样,null永远不可能是int)。你必须施放,使用三元组无法绕过它。

我不认为你会遇到与if语句相同的问题,因为编译器只会检查该方法是否从任何给定路径返回与返回类型相兼容的值,而不是来自任何给定路径的返回值出口点与另一个块的返回值隐式兼容。

0

?:运营商只有考虑其两个可能的返回值的类型。它不知道将接收其结果的变量的类型(的确,在更复杂的表达式中,可能不存在显式变量)。

如果其中一个返回值是null,它没有类型信息 - 它只能检查其他返回值的类型,并检查是否存在转换。我们有null和返回值类型int。没有可用的转换。有转换为int?,但这并不是?:正在考虑的可能的返回类型。