성태의 닷넷 이야기
홈 주인
모아 놓은 자료
프로그래밍
질문/답변
사용자 관리
사용자
메뉴
아티클
외부 아티클
유용한 코드
온라인 기능
MathJax 입력기
최근 덧글
[정성태] Roll A Lisp In C - Reading ; https...
[정성태] Java - How to use the Foreign Funct...
[정성태] 제가 큰 실수를 했군요. ^^; Delegate를 통한 Bein...
[정성태] Working with Rust Libraries from C#...
[정성태] Detecting blocking calls using asyn...
[정성태] 아쉽게도, 커뮤니티는 아니고 개인 블로그입니다. ^^
[정성태] 질문이 잘 이해가 안 됩니다. 우선, 해당 소스코드에서 ILis...
[양승조
] var대신 dinamic으로 선언해서 해결은 했습니다. 맞는 해...
[양승조
] 또 막혔습니다. ㅠㅠ var list = props[i].Ge...
[양승조
] 아. 감사합니다. 어제는 안됐던것 같은데....정신을 차려야겠네...
글쓰기
제목
이름
암호
전자우편
HTML
홈페이지
유형
제니퍼 .NET
닷넷
COM 개체 관련
스크립트
VC++
VS.NET IDE
Windows
Team Foundation Server
디버깅 기술
오류 유형
개발 환경 구성
웹
기타
Linux
Java
DDK
Math
Phone
Graphics
사물인터넷
부모글 보이기/감추기
내용
<div style='display: inline'> <h1 style='font-family: Malgun Gothic, Consolas; font-size: 20pt; color: #006699; text-align: center; font-weight: bold'>C# - 부모의 필드/프로퍼티에 대해 서로 다른 자식 클래스 간에 Reflection 접근이 동작할까요?</h1> <p> 제목만으로는 상황 설명이 안 되는군요. ^^ 역시 코드를 봐야 합니다.<br /> <br /> 예를 들어, 아래와 같은 상속 관계를 가질 때,<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > abstract class Base { <span style='color: blue; font-weight: bold'>public int Value = 50;</span> <span style='color: blue; font-weight: bold'>public abstract string Name { get; set; }</span> } class <span style='color: blue; font-weight: bold'>Derived1</span> : Base { string _name = "test1"; public override string Name { get => _name; set => _name = value; } } class <span style='color: blue; font-weight: bold'>Derived2</span> : Base { string _name = "test"; public override string Name { get => _name; set => _name = value; } } </pre> <br /> 상속을 받은 Derived1 타입을 기준으로 Type.GetField, Type.GetProperty를 호출해 얻은 FieldInfo, PropertyInfo가 (같은 부모 타입을 상속한) Derived2 타입을 기준으로 사용할 수 있을까요?<br /> <br /> 간단하게 테스트를 하면 됩니다. 우선, FieldInfo는,<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > FieldInfo? <span style='color: blue; font-weight: bold'>fi = typeof(Derived1)</span>.GetField("Value"); if (fi != null) { { <span style='color: blue; font-weight: bold'>Derived1 instance</span> = new Derived1(); Console.WriteLine(fi.GetValue(instance)); // 출력 결과: 50 } { <span style='color: blue; font-weight: bold'>Derived2 instance</span> = new Derived2(); Console.WriteLine(fi.GetValue(instance)); // 출력 결과: 50 } } </pre> <br /> 잘 동작합니다. 반면, PropertyInfo는,<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > PropertyInfo? <span style='color: blue; font-weight: bold'>pi = typeof(Derived1)</span>.GetProperty("Name"); if (pi != null) { { <span style='color: blue; font-weight: bold'>Derived1 instance</span> = new Derived1(); Console.WriteLine(pi.GetValue(instance)); // 출력 결과: test1 } { <span style='color: blue; font-weight: bold'>Derived2 instance</span> = new Derived2(); Console.WriteLine(pi.GetValue(instance)); // 예외 발생 } } </pre> <br /> Derived1으로 구한 PropertyInfo를 Derived2 타입의 인스턴스에 사용하면 예외가 발생합니다.<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > 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) </pre> <br /> 대신 Derived1이 아닌 부모 타입을 사용하면,<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > PropertyInfo? <span style='color: blue; font-weight: bold'>pi = typeof(Base)</span>.GetProperty("Name"); // ...[생략]... </pre> <br /> Derived1, Derived2 인스턴스 모두에서 예외 없이 잘 동작합니다.<br /> </p><br /> <br /><hr /><span style='color: Maroon'>[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]</span> </div>
첨부파일
스팸 방지용 인증 번호
2968
(왼쪽의 숫자를 입력해야 합니다.)