Microsoft MVP성태의 닷넷 이야기
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
(연관된 글이 1개 있습니다.)

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 메시지를 확인할 수 있습니다.

context_bound_object_reflection_1.png

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 열람을 막고 싶다면 이런 클래스를 그냥 정의해 두는 것만으로 효과가 있겠군요. ^^;)

(첨부 파일은 이 글의 테스트 코드를 포함합니다.)




[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]

[연관 글]






[최초 등록일: ]
[최종 수정일: 2/28/2024]

Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.
by SeongTae Jeong, mailto:techsharer at outlook.com

비밀번호

댓글 작성자
 



2016-02-21 03시43분
ContextBoundObject를 가끔씩 사용하는데 MSDN을 너무 띄엄띄엄 봤었나봅니다. Generic 지원을 못한다니... 왜 그런지 한반 찾아봤는데 별다른 이야기가 없네요.
Beren Ko
2016-02-21 11시49분
그래도 대단하시군요. ^^ 저는 알아두어야겠다는 생각으로만 ContextBoundObject를 봤을 뿐, 지금까지 한 번도 사용한 적이 없습니다. ^^;
정성태
2016-02-22 01시38분
그냥 처음에 이런게 있다는 걸 컬럼으로 봤다가 필요하다고 생각되는 경우가 있었어서 적용해 보았는데, 남들이 쓰지 않는 건 저같은 C#꼬꼬마들은 함부로 쓰지 않는 게 맞는 것 같습니다. 잘 알기도 쉽지 않고 문제가 생길 경우 뒷수습하기도 쉽지 않더라구요. ㅜㅜ
Beren Ko
2016-02-22 02시40분
그러게요. 뒷수습이 문제입니다. ^^ 게다가 후임이 ContextBoundObject를 보는 순간의 기분이란...?~~~!
정성태

1  2  3  4  5  6  7  8  9  10  11  12  13  [14]  15  ...
NoWriterDateCnt.TitleFile(s)
13280정성태3/9/20234605개발 환경 구성: 670. WSL 2에서 호스팅 중인 TCP 서버를 외부에서 접근하는 방법
13279정성태3/9/20234125오류 유형: 851. 파이썬 ModuleNotFoundError: No module named '_cffi_backend'
13278정성태3/8/20234156개발 환경 구성: 669. WSL 2의 (init이 아닌) systemd 지원 [1]
13277정성태3/6/20234812개발 환경 구성: 668. 코드 사인용 인증서 신청 및 적용 방법(예: Digicert)
13276정성태3/5/20234476.NET Framework: 2102. C# 11 - ref struct/ref field를 위해 새롭게 도입된 scoped 예약어
13275정성태3/3/20234792.NET Framework: 2101. C# 11의 ref 필드 설명
13274정성태3/2/20234356.NET Framework: 2100. C# - ref 필드로 ref struct 타입을 허용하지 않는 이유
13273정성태2/28/20234086.NET Framework: 2099. C# - 관리 포인터로서의 ref 예약어 의미
13272정성태2/27/20234357오류 유형: 850. SSMS - mdf 파일을 Attach 시킬 때 Operating system error 5: "5(Access is denied.)" 에러
13271정성태2/25/20234274오류 유형: 849. Sql Server Configuration Manager가 시작 메뉴에 없는 경우
13270정성태2/24/20233872.NET Framework: 2098. dotnet build에 /p 옵션을 적용 시 유의점
13269정성태2/23/20234436스크립트: 46. 파이썬 - uvicorn의 콘솔 출력을 UDP로 전송
13268정성태2/22/20234988개발 환경 구성: 667. WSL 2 내부에서 열고 있는 UDP 서버를 호스트 측에서 접속하는 방법
13267정성태2/21/20234898.NET Framework: 2097. C# - 비동기 소켓 사용 시 메모리 해제가 finalizer 단계에서 발생하는 사례파일 다운로드1
13266정성태2/20/20234506오류 유형: 848. .NET Core/5+ - Process terminated. Couldn't find a valid ICU package installed on the system
13265정성태2/18/20234432.NET Framework: 2096. .NET Core/5+ - PublishSingleFile 유형에 대한 runtimeconfig.json 설정
13264정성태2/17/20235932스크립트: 45. 파이썬 - uvicorn 사용자 정의 Logger 작성
13263정성태2/16/20234087개발 환경 구성: 666. 최신 버전의 ilasm.exe/ildasm.exe 사용하는 방법
13262정성태2/15/20235158디버깅 기술: 191. dnSpy를 이용한 (소스 코드가 없는) 닷넷 응용 프로그램 디버깅 방법 [1]
13261정성태2/15/20234422Windows: 224. Visual Studio - 영문 폰트가 Fullwidth Latin Character로 바뀌는 문제
13260정성태2/14/20234230오류 유형: 847. ilasm.exe 컴파일 오류 - error : syntax error at token '-' in ... -inf
13259정성태2/14/20234377.NET Framework: 2095. C# - .NET5부터 도입된 CollectionsMarshal
13258정성태2/13/20234265오류 유형: 846. .NET Framework 4.8 Developer Pack 설치 실패 - 0x81f40001
13257정성태2/13/20234353.NET Framework: 2094. C# - Job에 Process 포함하는 방법 [1]파일 다운로드1
13256정성태2/10/20235187개발 환경 구성: 665. WSL 2의 네트워크 통신 방법 - 두 번째 이야기
13255정성태2/10/20234517오류 유형: 845. gihub - windows2022 이미지에서 .NET Framework 4.5.2 미만의 프로젝트에 대한 빌드 오류
1  2  3  4  5  6  7  8  9  10  11  12  13  [14]  15  ...