Microsoft MVP성태의 닷넷 이야기
오류 유형: 103. System.Reflection.TargetException [링크 복사], [링크+제목 복사],
조회: 27070
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일

System.Reflection.TargetException

특수한 경우이긴 하지만. 기록을 남기는 차원에서. ^^

상황은 다음과 같습니다.

public class BaseA
{
    public int Field
    {
        get; set;
    }
}

public class DerivedB : BaseA {}

public class DerivedC : BaseA {}

위와 같은 구조에서 BaseA.Field를 접근하는 데 Reflection을 이용해서 다음과 같이 사용을 합니다.

static void Main(string[] args)
{
    DerivedB db = new DerivedB();
    Console.WriteLine(GetFieldValue(db));

    DerivedC dc = new DerivedC();
    Console.WriteLine(GetFieldValue(dc));
}

static PropertyInfo propertyInfo;
static int GetFieldValue(object instance)
{
    if (propertyInfo == null)
    {
        propertyInfo = instance.GetType().GetProperty("Field", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public);
    }

    return (int)propertyInfo.GetValue(instance, null);
}

상황에 따라서, 해당 어셈블리를 직접 참조할 수 없어서 public 필드에 대한 접근조차도 Reflection을 이용해야 할 필요가 있습니다. 어쨌든, 위의 코드는 PropertyInfo를 캐쉬해서 정상적으로 대부분의 코드에서 잘 사용할 수 있었는데요.

예상치 않게, 특정 클래스에 대해 다음과 같은 오류가 발생했습니다.

System.Reflection.TargetException occurred
  Message=Object does not match target type.
  Source=mscorlib
  StackTrace:
       at System.Reflection.RuntimeMethodInfo.CheckConsistency(Object target)
       at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture, Boolean skipVisibilityChecks)
       at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
       at System.Reflection.RuntimePropertyInfo.GetValue(Object obj, BindingFlags invokeAttr, Binder binder, Object[] index, CultureInfo culture)
       at System.Reflection.RuntimePropertyInfo.GetValue(Object obj, Object[] index)
       at Jennifer40.Profiler.Interception.SoapHttpClientProtocolInvoke2000_Preprocess(Object thisObject, Boolean& bEndProcess, String arg1, Object[] arg2)
  InnerException: 

갑자기 ^^; GetProperty를 사용한 Reflection에 대한 급(!) 회의감이 들었습니다.

위의 예에서는 문제를 간략화했기 때문에 분석이 간단하지만, 건드릴 수 없는 고객사의 복잡한 웹 애플리케이션 코드와 제 코드가 뒤섞여서 발생하는 상황이라면 저 정도의 오류 메시지로 문제 분석할 엄두가 나질 않습니다. ^^;

(하지만, 삶은 계속되므로!) 문제를 분석하는 중... TargetException이 발생하는 클래스들의 공통점이 발견되었습니다. 바로, 해당 Field에 대해서 상속받은 클래스에서 재정의를 한 경우였습니다.

바로 이렇게, virtual/override 로 했거나,

public class BaseA
{
    public virtual int Field { get; set; }
}

public class DerivedB : BaseA
{
    public override int Field { get; set; }
}

public class DerivedC : BaseA
{
    public override int Field { get; set; }
}

또는, new로 했거나,

public class BaseA
{
    public int Field { get; set; }
}

public class DerivedB : BaseA
{
    public new int Field { get; set; }
}

public class DerivedC : BaseA
{
    public new int Field { get; set; }
}

그런 경우에, 아래와 같이 instance.GetType().GetProperty로 반환받으면 상속받은 클래스의 필드가 나오게 됩니다.

instance.GetType().GetProperty("Field", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public);

따라서, DerivedB.Field에 대한 PropertyInfo를 캐쉬하고 있었는데 DerivedC 인스턴스가 들어오니 System.Reflection.TargetException 예외가 발생한 것입니다.

이를 해결하려면?

만약, 기반 클래스의 Field 접근이 원하는 값을 반환해 준다면 다음과 같이 명시적인 타입을 지정해 줄 수 있습니다.

Type targetType = ...[BaseA 타입 구하는 코드]...;
targetType.GetProperty(...);

그렇지 않다면, static 캐쉬를 포기해야 합니다. 그냥 인스턴스 변수에 저장해 놓고 그때그때의 타입에 따라 매번 GetProperty를 구해서 처리해야 합니다. (위의 경우에는 속성만 예를 들었지만, 일반 메서드의 경우에도 동일하게 적용되겠죠!)

결국은, ... 이번 문제는 아는 게 병이 된 좋은 사례라는. ^^;



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







[최초 등록일: ]
[최종 수정일: 6/23/2021]

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

비밀번호

댓글 작성자
 




... 151  152  153  154  155  156  157  [158]  159  160  161  162  163  164  165  ...
NoWriterDateCnt.TitleFile(s)
1094정성태8/14/201130423오류 유형: 131. Fiddler가 강제 종료된 경우, 웹 사이트 방문이 안되는 현상
1093정성태7/27/201124053오류 유형: 130. Unable to connect to the Microsoft Visual Studio Remote Debugging Monitor ... Access is denied.
1092정성태7/22/201126447Team Foundation Server: 46. 코드 이외의 파일에 대해 소스 제어에서 제외시키는 방법
1091정성태7/21/201125469개발 환경 구성: 128. WP7 Emulator 실행 시 audiodg.exe의 CPU 소모율 증가 [2]
1089정성태7/18/201131033.NET Framework: 234. 왜? Button 컨트롤에는 MouseDown/MouseUp 이벤트가 발생하지 않을까요?파일 다운로드1
1088정성태7/16/201124172.NET Framework: 233. Entity Framework 4.1 - 윈도우 폰 7에서의 CodeFirst 순환 참조 문제파일 다운로드1
1087정성태7/15/201126783.NET Framework: 232. Entity Framework 4.1 - CodeFirst 개체의 직렬화 시 순환 참조 해결하는 방법 - 두 번째 이야기파일 다운로드1
1086정성태7/14/201128252.NET Framework: 231. Entity Framework 4.1 - CodeFirst 개체의 직렬화 시 순환 참조 해결하는 방법 [1]파일 다운로드1
1085정성태7/14/201128678.NET Framework: 230. Entity Framework 4.1 - Code First + WCF 서비스 시 EndpointNotFoundException 오류 - 두 번째 이야기파일 다운로드1
1084정성태7/11/201133963.NET Framework: 229. SQL 서버 - DB 테이블의 데이터 변경에 대한 알림 처리 [4]파일 다운로드1
1083정성태7/11/201128001.NET Framework: 228. Entity Framework 4.1 - Code First + WCF 서비스 시 EndpointNotFoundException 오류
1082정성태7/10/201127581.NET Framework: 227. basicHttpBinding + 사용자 정의 인증 구현 [2]파일 다운로드1
1081정성태7/9/201126914VC++: 53. Windows 7에서 gcc.exe 실행 시 Access denied 오류 [2]
1080정성태7/8/201125407웹: 23. Sysnet 웹 사이트의 HTML5 변환 기록 - 두 번째 이야기파일 다운로드1
1079정성태7/6/201129841오류 유형: 129. Hyper-V + Realtek 랜카드가 설치된 시스템의 BSOD 현상 [2]
1078정성태7/5/201137388VC++: 52. Chromium 컴파일하는 방법 [2]
1077정성태6/24/201135023.NET Framework: 226. HttpWebRequest 타입의 HaveResponse 속성 이야기파일 다운로드1
1076정성태6/23/201129113오류 유형: 128. SQL Express - User Instance 옵션을 사용한 경우 발생하는 오류 메시지 유형 2가지
1075정성태6/21/201124777VS.NET IDE: 69. 윈폰 프로젝트에서 WCF 서비스 참조할 때 Reference.cs 파일이 비어있는 경우
1074정성태6/20/201124857.NET Framework: 225. 닷넷 네트워크 라이브러리의 트레이스 기능파일 다운로드1
1073정성태6/20/201127085오류 유형: 127. Visual Studio에서 WCF 서비스의 이름 변경 시 발생할 수 있는 오류
1072정성태6/19/201126546.NET Framework: 224. EF 4.1 Code First에서 Identity 칼럼 생성하는 방법파일 다운로드1
1071정성태6/19/201130053.NET Framework: 223. Entity Framework 4.1의 Code First를 이용한 SQL Azure 데이터베이스 생성 [3]파일 다운로드1
1070정성태6/19/201127586.NET Framework: 222. Windows Azure - VM Role 베타 프로그램 참여 [2]
1069정성태6/18/201127692.NET Framework: 221. Cache 영향을 받지 않는 DNS 이름 풀이 [2]파일 다운로드1
1068정성태6/16/201125314개발 환경 구성: 127. Portable Library - 닷넷 N-Screen용 공통 라이브러리 제작 [1]
... 151  152  153  154  155  156  157  [158]  159  160  161  162  163  164  165  ...