2016-06-21 3 views
-2

나는 약간의 List<T> 속성을 가진 클래스가 있습니다. 주어진 목록의 크기를 동적으로 결정할 수 있어야합니다.리플렉션을 사용하여 목록의 항목 수를 얻는 방법

아래 코드는 제가 지금까지 가지고있는 코드입니다. switch 문을 없애고 이것을 하나의 일반적인 문으로 사용할 수 있습니까? List<T>으로 전송하고 싶지만 작동하지 않습니다. 일반 입력 된 List<> 인터페이스 IList를 구현하므로

switch (Inf.GetType() 
      .GetProperty(propertyName) 
      .GetValue(Inf) 
      .GetType() 
      .UnderlyingSystemType.GenericTypeArguments[0] 
      .Name) 
     { 
      case "String": 
       dynamicListCount = ((List<string>)Inf.GetType().GetProperty(propertyName).GetValue(Inf)).Count; 
       break; 
      case "Int32": 
       dynamicListCount = ((List<Int32>)Inf.GetType().GetProperty(propertyName).GetValue(Inf)).Count; 
       break; 
      default: 
       throw new Exception("Unknown list type"); 
     } 
+4

당신이 IList''로 캐스팅하지 왜? –

+0

'List '을 사용하지 않는 이유를 모르십니까? .Count –

답변

2

List<T>은 (ICollection로부터 상속)을 Count 속성이 IList을 구현한다.

당신은 단순히 IList으로 값을 캐스팅하고이 같은 수를 얻을 수 있습니다 :

IList list = (IList) Inf.GetType() 
     .GetProperty(propertyName) 
     .GetValue(Inf); 

var count = list.Count; 
+0

IList로 전송 해 보았습니다. 감사! – Carl

2

당신은 IList에 배역한다. 같은 의견은 제안하고 있습니다. (올리지)

List<string> items = new List<string>(); 

items.Add("item1"); 
items.Add("item2"); 


int count = ((IList)items).Count; 

MessageBox.Show(count.ToString()); 
관련 문제