2012-10-15 3 views
3

nullable struct을 되돌려주는 함수가 있습니다. 둘째null 값을 nullable 구조체로 변환해야하는 이유

public static GeometricCircle? CircleBySize(GeometricPoint point, double size) 
{ 
    if (size >= epsilon) 
     return null; 

    return new GeometricCircle(point.Position, new Vector(1, 0, 0), size, true); 
} 

을 : 잘 작동 : GeometricCircle에 null 값을 변환해야합니다 나는 두 개의 유사한 경우

먼저

을 발견?

public static GeometricCircle? CircleBySize(GeometricPoint point, double size) 
{ 
    return size > epsilon ? new GeometricCircle(point.Position, new Vector(1, 0, 0), size, true) : (GeometricCircle?)null; 
} 

아무도 그 차이점을 알고 있습니까?

+0

GeometricCircle이 클래스 인 경우 캐스팅이 필요하지 않습니다. 제 생각에는. – ragatskynet

+0

당신은 절대적으로 옳습니다. 그 클래스는 클래스가 아니라 구조체입니다. 그러나 질문은 나에게 여전히 남아있다. 차이점은 무엇인가? –

+2

중복 가능성이 있습니까? http://stackoverflow.com/questions/858080/nullable-types-and-the-ternary-operator-why-is-10-null-forbidden – Silvermind

답변

5

첫 번째 예에서는 size >= epsilon 일 때 null을 반환합니다. 컴파일러는 null이 Null 허용 유형에 유효한 값임을 알고 있습니다.

두 번째 예에서는 자체 규칙 세트와 함께 제공되는 ?: ternary operator을 사용하고 있습니다.

condition ? first_expression : second_expression; 

MSDN 알려줍니다 우리 (내 강조) ...

어느 first_expressionsecond_expression의 유형이 동일하거나 암시 적 변환 하나 개의 유형에서 다른 존재해야해야합니다. 여기

의 주요 차이점은 null가 암시 적으로GeometricCircle로 변환합니다 (first_expression의 종류)이 될 수 없다는 것입니다.

그래서 당신은 그 GeometricCircle에 암시 적으로 전환 입니다 GeometricCircle?에 캐스트를 사용하여, 그것을 명시 적으로을해야한다.

+0

일단 IL로 컴파일 된 삼항 연산자는 무엇입니까? – Guillaume

+0

null은 암시 적으로 nullable 로 변환 될 수 있지만 GeometricCircle로 변환 될 수는 없습니다. –

관련 문제