DEV/Unity C#

[C#] structs and Interface

ssapo 2019. 6. 1. 13:31
반응형

The fact that a struct can implement an interface is well known and so is the fact that casting a value type into an interface leads to boxing of the value type. This is because methods in interfaces are defined as virtual and to resolve virtual references, vtable (method table) look up is required. Since value types do not have pointers to vtable they are first boxed into a reference type and then the look up happens.

 

구조체가 인터페이스를 구현할 수 있다는 사실은 잘 알려져 있고 값 유형을 인터페이스에 캐스팅하면 값 유형의 복싱으로 연결된다는 사실도 있습니다. 이것은 인터페이스의 메소드가 가상으로 정의되고 가상 참조를 분석하기 때문에 vtable (메소드 테이블) 검색이 필요합니다. 값 유형에는 vtable에 대한 포인터가 없기 때문에 먼저 참조 유형으로 묶인 다음 조회가 발생합니다.

 

This boxing leads to some performance penalty. See Rico Mariani's performance quiz for an example.

 

이 복싱은 약간의 성능 저하를 초래합니다. 예를 들어 Rico Mariani의 성능 퀴즈를 참조하십시오.

 

The fact that such boxing takes place on casting to interfaces can lead to subtle issues in code. Consider the following

 

이러한 복싱이 인터페이스로 캐스팅 될 때 발생한다는 사실은 코드에서 미묘한 문제를 일으킬 수 있습니다. 다음을 고려하세요

 

Here the output would be 
Cool Guy (65)
Cool Guy (65)


So even after calling p.promote() the value of JobGrade in employee does not increase. The reason is that on implicitly casting employee to IPromotion p a temporary boxed object is created and p.promote updates the JobGrade in this temporary object and not on original employee value type. Since after this usage the temporary boxed object is not refered to, the update to it is lost and it is garbage collected.

 

따라서 p.promote ()를 호출 한 후에도 Employer의 JobGrade 값은 증가하지 않습니다. 그 이유는 직원을 IPromotion p에 암시 적으로 캐스팅 할 때 임시 boxed 객체가 생성되고 p.promote가 원래 임시 값 유형이 아닌이 임시 객체의 JobGrade를 업데이트하기 때문입니다. 이 사용법 이후에 임시 boxed 객체는 참조되지 않기 때문에, 그것의 업데이트는 손실되고 가비지 수집됩니다.

 

If however we change the code and make Employee a class the output would become as expected

 

그러나 코드를 변경하고 Employee를 클래스로 만들면 출력이 예상대로 될 것입니다.

 

Cool Guy (65)
Cool Guy (66)

 

The reason being that now the boxing does not take place and the update happens on the original employee object.

 

그 이유는 지금 복싱이 발생하지 않고 업데이트가 원래 직원 개체에서 발생하기 때문입니다.

반응형