Microsoft MVP성태의 닷넷 이야기
Reflection 관련 질문 드립니다. [링크 복사], [링크+제목 복사],
조회: 8306
글쓴 사람
양승조 donator
홈페이지
첨부 파일
 

안녕하세요. 선생님 Reflection 관련 질문 드립니다.

클래스 내에 여러가지 프로퍼티를 선언하여 사용하고 있고, 그 프로퍼티들을 아래와 같이 접근하여 사용하고 있습니다.
일반 프로퍼티는 SetValue나 GetValue 모두 접근이 가능합니다.
문제는 List 형태의 Property에 접근시 문제가 됩니다.
아래는 코드 입니다.

{
    var props = this.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance);
    for(int i = 0; i < props.Length; i++)
    {
        string nameofType = this.GetType().Name;
        string name = props[i].Name;
        string type = props[i].GetType().ToString();

        if (typeof(System.Collections.IList).IsAssignableFrom(props[i].PropertyType))
        {
            //var list = props[i].GetValue(props[i]) as IEnumerable;
            //List<bool> another = props[i].GetValue(props[i]) as List<bool>;
        }
        else
        {
            object readValue2 = Convert.ChangeType(readValue, props[i].PropertyType);
            props[i].SetValue(this, readValue2);
        }
    }
}

if문에서 리스트 타입인지 확인 후 아래에서 GetValue로 List를 받아 처리하려고 합니다.
여러가지 검색내용을 적용해 보았고, 위 코드에서 if문안에 주석처리된 부분과 같이 적용해 보았으나,
아래와 같은 예외가 발생합니다.

Exception thrown: 'System.Reflection.TargetException' in System.Private.CoreLib.dll
An unhandled exception of type 'System.Reflection.TargetException' occurred in System.Private.CoreLib.dll
Object does not match target type.

감사합니다.








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


비밀번호

댓글 작성자
 



2024-04-24 11시38분
저렇게 조각 코드 말고, 실제로 재현이 되는 예제 프로젝트를 압축해서 올려주세요.
정성태

NoWriterDateCnt.TitleFile(s)