2011-07-01 2 views
2
using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 

namespace ConsoleApplication1 
{ 
    class User 
    { 
     public int? Age { get; set; } 
     public int? ID { get; set; } 
    } 

    class Program 
    { 
     static void Main(string[] args) 
     { 
      User user = new User(); 
      user.Age = null;  // no warning or error 
      user.ID = (int?)null; // no warning or error 

      string result = string.Empty; 
      User user2 = new User 
          { 
       Age = string.IsNullOrEmpty(result) ? null : Int32.Parse(result), 
       // Error 1 Type of conditional expression cannot be determined 
       // because there is no implicit conversion between '<null>' and 'int' 
       // ConsoleApplication1\ConsoleApplication1\Program.cs 23 71 ConsoleApplication1 

       ID = string.IsNullOrEmpty(result) ? (int?)null : Int32.Parse(result) // // no warning or error 
          }; 
     } 
    } 
} 

질문 :왜 개체 이니셜 라이저를 사용할 때 use (int?) null입니까?

다음 줄이 작동하지 않는 이유는 무엇입니까?

Age = string.IsNullOrEmpty(result) ? null : Int32.Parse(result) 

// 수정 한

Age = string.IsNullOrEmpty(result) ? (int?) null : Int32.Parse(result) 

이유는 다음 줄의 작품이다?

user.Age = null;  // no warning or error 
+0

참조 http://stackoverflow.com/questions/1171717 –

답변

3
Age = string.IsNullOrEmpty(result) ? null : Int32.Parse(result) 

이 작동하지 않습니다.

컴파일러는 string.IsNullOrEmpty(result) ? null : Int32.Parse(result)이 어떤 종류인지 알 수 없습니다.

먼저 참조 유형임을 나타내는 null이 표시되고 호환되지 않는 값 유형 인 int이 표시됩니다. int에서 int?까지 암시 적 형변환 연산자가있는 형식이 컴파일러에서 유추되지 않습니다.

이론 상으로는 충분히 이해할 수 있지만 컴파일러는 더 정교해질 필요가 있습니다.

2

C#은 모든 표현식에 유형이 있어야하기 때문에. 컴파일러는 작동하지 않는 행에서 3 진 표현식의 유형을 판별 할 수 없습니다.

6

왜냐하면 3 진 연산자는 반환 유형이 동일한 유형이어야하기 때문입니다.

첫 번째 경우 "null"은 어떤 참조 유형 (int가 아닌)의 null 일 수 있으므로 캐스팅 할 필요가있는 컴파일러에 명시 적으로 만들 수 있습니다.

그렇지 않으면 당신은 분명 비트 cuckooo입니다

string x = null; 
Age = string.IsNullOrEmpty(result) ? x: Int32.Parse(result) 

있을 수 있습니다.

2

인라인 연산자 nullint 인 경우 연산자가 반환 할 형식을 알 수 없습니다. int은 null이 될 수 없기 때문에 컴파일러는 ?:이 반환 한 유형을 해결할 수 없습니다. string.IsNullOrEmpty(result) ? null : Int32.Parse(result)Age = 부분을 별도로 평가하기 때문에

관련 문제