Microsoft MVP성태의 닷넷 이야기
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일

(시리즈 글이 11개 있습니다.)
.NET Framework: 404. 리플렉션을 이용해 닷넷 LicenseManager를 우회할 수 있는 사례
; https://www.sysnet.pe.kr/2/0/1565

.NET Framework: 428. .NET Reflection으로 다차원/Jagged 배열을 구분하는 방법
; https://www.sysnet.pe.kr/2/0/1653

.NET Framework: 537. C# - Reflection의 박싱 없이 값 형식을 다루는 방법
; https://www.sysnet.pe.kr/2/0/10866

.NET Framework: 685. C# - 구조체(값 형식)의 필드를 리플렉션을 이용해 값을 바꾸는 방법
; https://www.sysnet.pe.kr/2/0/11312

.NET Framework: 785. public으로 노출되지 않은 다른 어셈블리의 delegate 인스턴스를 Reflection으로 생성하는 방법
; https://www.sysnet.pe.kr/2/0/11583

.NET Framework: 842. .NET Reflection을 대체할 System.Reflection.Metadata 소개
; https://www.sysnet.pe.kr/2/0/11930

.NET Framework: 924. C# - Reflection으로 변경할 수 없는 readonly 정적 필드
; https://www.sysnet.pe.kr/2/0/12256

.NET Framework: 1045. C# - 런타임 시점에 이벤트 핸들러를 만들어 Reflection을 이용해 구독하는 방법
; https://www.sysnet.pe.kr/2/0/12609

.NET Framework: 1046. C# - 컴파일 시점에 참조할 수 없는 타입을 포함한 이벤트 핸들러를 Reflection을 이용해 구독하는 방법
; https://www.sysnet.pe.kr/2/0/12610

닷넷: 2155. C# - .NET 8 런타임부터 (Reflection 없이) 특성을 이용해 public이 아닌 멤버 호출 가능
; https://www.sysnet.pe.kr/2/0/13436

닷넷: 2249. C# - 부모의 필드/프로퍼티에 대해 서로 다른 자식 클래스 간에 Reflection 접근이 동작할까요?
; https://www.sysnet.pe.kr/2/0/13608




C# - 부모의 필드/프로퍼티에 대해 서로 다른 자식 클래스 간에 Reflection 접근이 동작할까요?

제목만으로는 상황 설명이 안 되는군요. ^^ 역시 코드를 봐야 합니다.

예를 들어, 아래와 같은 상속 관계를 가질 때,

abstract class Base
{
    public int Value = 50;

    public abstract string Name { get; set; }
}

class Derived1 : Base
{
    string _name = "test1";
    public override string Name { get => _name; set => _name = value; }
}

class Derived2 : Base
{
    string _name = "test";
    public override string Name { get => _name; set => _name = value; }
}

상속을 받은 Derived1 타입을 기준으로 Type.GetField, Type.GetProperty를 호출해 얻은 FieldInfo, PropertyInfo가 (같은 부모 타입을 상속한) Derived2 타입을 기준으로 사용할 수 있을까요?

간단하게 테스트를 하면 됩니다. 우선, FieldInfo는,

FieldInfo? fi = typeof(Derived1).GetField("Value");
if (fi != null)
{
    {
        Derived1 instance = new Derived1();
        Console.WriteLine(fi.GetValue(instance)); // 출력 결과: 50
    }

    {
        Derived2 instance = new Derived2();
        Console.WriteLine(fi.GetValue(instance)); // 출력 결과: 50
    }
}

잘 동작합니다. 반면, PropertyInfo는,

PropertyInfo? pi = typeof(Derived1).GetProperty("Name");
if (pi != null)
{
    {
        Derived1 instance = new Derived1();
        Console.WriteLine(pi.GetValue(instance)); // 출력 결과: test1
    }

    {
        Derived2 instance = new Derived2();
        Console.WriteLine(pi.GetValue(instance)); // 예외 발생
    }
}

Derived1으로 구한 PropertyInfo를 Derived2 타입의 인스턴스에 사용하면 예외가 발생합니다.

Unhandled Exception: System.Reflection.TargetException: Object does not match target type.
   at System.Reflection.RuntimeMethodInfo.CheckConsistency(Object target)
   at System.Reflection.RuntimeMethodInfo.InvokeArgumentsCheck(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
   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 System.Reflection.PropertyInfo.GetValue(Object obj)
   at ConsoleApp1.Program.Main(String[] args)

대신 Derived1이 아닌 부모 타입을 사용하면,

PropertyInfo? pi = typeof(Base).GetProperty("Name");
// ...[생략]...

Derived1, Derived2 인스턴스 모두에서 예외 없이 잘 동작합니다.




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







[최초 등록일: ]
[최종 수정일: 4/26/2024]

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)
920정성태9/1/201034802오류 유형: 105. WMI - The RPC server is unavailable [2]
919정성태8/30/201040909DDK: 1. Visual Studio 2010 - Device Driver 제작- Hello World 예제 [3]파일 다운로드1
918정성태8/28/201027018개발 환경 구성: 87. Hyper-V의 네트워크 유형 (3)
917정성태8/26/201021992개발 환경 구성: 86. "Routing and Remote Access"의 "Routing" 기능 활성화 방법
916정성태8/25/201021237개발 환경 구성: 85. 가상 네트워크에 LAN 어댑터 보이거나 감추는 방법
915정성태8/24/201039323개발 환경 구성: 84. Hyper-V의 네트워크 유형 (2)
913정성태8/22/201028474오류 유형: 104. Hyper-V 관리자 - VM 생성 오류 (VHD 생성 오류)
912정성태8/20/201030374.NET Framework: 183. 구조체 포인터 인자에 대한 P/Invoke 정의파일 다운로드1
911정성태8/19/201027240오류 유형: 103. System.Reflection.TargetException파일 다운로드1
910정성태8/19/201038049개발 환경 구성: 83. Hyper-V의 네트워크 유형 (1)
909정성태8/18/201033414오류 유형: 102. System.MissingMethodException
908정성태8/17/201024449개발 환경 구성: 82. Windows Virtual PC의 네트워크 유형 (3)
907정성태8/14/201022004개발 환경 구성: 81. Windows Virtual PC의 네트워크 유형 (2)
906정성태8/13/201030833개발 환경 구성: 80. Windows Virtual PC의 네트워크 유형 (1)
905정성태8/8/201032974Team Foundation Server: 39. 배치 파일로 팀 빌드 구성 [2]파일 다운로드1
904정성태8/8/201035798오류 유형: 101. SignTool Error: No certificates were found that met all the given criteria. [2]
903정성태8/6/201032651Team Foundation Server: 38. TFS 소스 코드 관리 기능 (4) - Branch
902정성태8/5/201025039Team Foundation Server: 37. TFS 2010의 소스 서버 수작업 구성
901정성태8/4/201024295Team Foundation Server: 36. TFS 소스 코드 관리 기능 (3) - Label
900정성태8/3/201026981Team Foundation Server: 35. TFS 소스 코드 관리 기능 (2) - Shelveset
899정성태8/2/201029005Team Foundation Server: 34. TFS 소스 코드 관리 기능 (1) - Changeset
898정성태7/31/201028490.NET Framework: 182. WCF의 InactivityTimeout [1]파일 다운로드1
897정성태7/26/201129698.NET Framework: 181. AssemblyVersion, AssemblyFileVersion, AssemblyInformationalVersion [4]
896정성태7/25/201036520.NET Framework: 180. C# Singleton 인스턴스 생성 [2]
895정성태7/25/201020432VS.NET IDE: 68. Visual Studio 2010 - .NET 1.1 원격 디버깅
894정성태7/25/201026371오류 유형: 100. Could not find the Database Engine startup handle. [1]
... 151  152  153  154  155  156  157  158  159  160  161  162  163  164  [165]  ...