2016-08-26 5 views
3

다음과 같은 클래스 구조가 있습니다. 이 오류가 발생합니다. 내가 여기서 뭔가를 놓치고 있니?리플렉션을 사용하여 클래스 인스턴스의 제네릭 목록 속성에 개체를 추가하는 방법

개체가 대상 유형과 일치하지 않습니다. 내가 노력하고 무엇

클래스 구조

public class Schedule 
{ 
    public Schedule() { Name = ""; StartDate = DateTime.MinValue; LectureList = new List<Lecture>(); } 
    public string Name { get; set; } 
    public DateTime StartDate { get; set; } 
    public List<Lecture> LectureList { get; set; } 
} 

public class Lecture 
{ 
    public string Name { get; set; } 
    public int Credit { get; set; } 
} 

는 :

// gets metadata of List<Lecture>.Add method 
var addMethod = pi.PropertyType.GetMethod("Add"); 

// retrieves current LectureList value to call Add method 
var lectureList = pi.GetValue(s); 

// calls s.LectureList.Add(obj); 
addMethod.Invoke(lectureList, new object[] { obj }); 

UPD :

Schedule s = new Schedule(); 
Type t = Type.GetType("Lecture"); 
object obj = Activator.CreateInstance(t); 
obj.GetType().GetProperty("Name").SetValue(obj, "Math"); 
obj.GetType().GetProperty("Credit").SetValue(obj, 1); 
PropertyInfo pi = s.GetType().GetProperty("LectureList"); 
Type ti = Type.GetType(pi.PropertyType.AssemblyQualifiedName); 
ti.GetMethod("Add").Invoke(pi, new object[] { obj }); 
+0

문제를 재현하려고 노력하는 동안, 나는 또 다른 문제를 발견했다. 문자열 인 동안'Credit '을'1'로 설정합니다. 유형을 int로 변경하십시오. –

+0

@stuartd 내가 반사를 올바르게 사용하는 이유가 있습니까? – Helio

+0

코드 조각을 만들었을 때이 문 뒤에 null 값이 있습니다. Type t = Type.GetType ("Lecture"); 분명히 다음 문장은 null ref 예외를 던지 겠지만, 당신이 가진 메시지는 다른 것입니다. 그때 존 소총에서 대답 아래 이것 좀 봐, Type.GetType의 사용은 (경우에 경우) 문제가 될 수 있습니다 볼 수 있었다 - http://stackoverflow.com/a/1044472/1966993 –

답변

1

그것은이 같은해야한다. 여기는 바이올린 link입니다.

+0

감사 - 단지'PropertyInfo.PropertyType'를 사용합니다. – Helio

+0

누락 무슨 대답, .GetValue (들)에 대한 – Dennis

1

List<Lecture>Add 메서드를 가져와 메서드 호출 인스턴스로 PropertyInfo과 함께 호출하면 문제가 발생합니다.

변경 :

ti.GetMethod("Add").Invoke(pi, new object[] { obj }); 

에 :

object list = pi.GetValue(s); 
ti.GetMethod("Add").Invoke(list, new object[] { obj }); 

pi.GetValue(s) 만의 getset 방법과 함께 재산 자체를 나타내는 PropertyInfo에서 List<Lecture> 자체 (및이 호출됩니다 그 방법은 귀하의 object[]을 인수로 사용하여 Add 방법을 사용하십시오.


한 가지 더. 사용하는 이유 :

Type ti = Type.GetType(pi.PropertyType.AssemblyQualifiedName); 

당신은 사용할 수있는 경우 :

Type ti = pi.PropertyType;