ContextBoundObject 상속 클래스와 System.Reflection.ReflectionTypeLoadException 예외
제목 짓기가 영 난감하군요. ^^
암튼, 다음의 간단한 프로그램을 실행하면,
using System;
using System.Reflection;
class Program
{
static void Main(string[] args)
{
Assembly asm = typeof(Program).Assembly;
foreach (Type type in asm.GetTypes())
{
Console.WriteLine(type.FullName);
}
}
}
class Test<T> : ContextBoundObject
{
public Test()
{
}
}
asm.GetTypes 호출 시 예외가 발생합니다.
An unhandled exception of type 'System.Reflection.ReflectionTypeLoadException' occurred in mscorlib.dll
Additional information: Unable to load one or more of the requested types. Retrieve the LoaderExceptions property for more information.
Unhandled Exception: System.Reflection.ReflectionTypeLoadException: Unable to load one or more of the requested types. Retrieve the LoaderExceptions property for more information.
at System.Reflection.RuntimeModule.GetTypes(RuntimeModule module)
at System.Reflection.RuntimeModule.GetTypes()
at System.Reflection.Assembly.GetTypes()
at Program.Main(String[] args) in E:\...\ConsoleApplication1\Program.cs:line 9
재미있는 것은, 저 소스 코드에서 아래의 2가지 변경 사항 중 하나라도 적용하면 예외가 발생하지 않습니다.
- Test 제네릭 타입을 일반 타입으로 전환한 경우
- ContextBoundObject 상속을 받지 않는 경우
즉, ContextBoundObject이면서 제네릭 타입을 정의한 어셈블리의 GetTypes 호출은 예외가 발생하는 것입니다.
이유는 간단합니다. 원래 ContextBoundObject 상속 클래스는 제네릭이어서는 안된다는 간단한 제약이 있기 때문입니다. 실제로 비주얼 스튜디오 디버깅으로 통해 보면 다음과 같은 LoaderExceptions 메시지를 확인할 수 있습니다.
Generic context-bound objects are not supported. : Test`1
물론 도움말에도 나와 있습니다. ^^
ContextBoundObject Class
; https://learn.microsoft.com/en-us/dotnet/api/system.contextboundobject
Notes to Implementers:
The current version of the common language runtime does not support generic ContextBoundObject types or nongeneric ContextBoundObject types that have generic methods. Attempting to create an instance of such a type causes a TypeLoadException.
단지, 문제는? 컴파일러로 하여금 이런 클래스를 만드는 것이 문제가 안되고 런타임 시에만 Type Loader에 의해 오류가 발생한다는 점입니다.
(그나저나... 의도한 것은 아니지만... 다른 프로그램이 GetTypes로 Reflection 열람을 막고 싶다면 이런 클래스를 그냥 정의해 두는 것만으로 효과가 있겠군요. ^^;)
(
첨부 파일은 이 글의 테스트 코드를 포함합니다.)
[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]