2009-06-01 2 views
13

이 (단축) 코드 ..PropertyInfo.GetValue() - C#에서 리플렉션을 사용하여 제네릭 매개 변수에 어떻게 인덱싱합니까? '파라미터 카운트 불일치 TargetParameterCountException'예외

for (int i = 0; i < count; i++) 
{ 
    object obj = propertyInfo.GetValue(Tcurrent, new object[] { i }); 
} 

의 .. 던지고.

'propertyInfo'의 기본 유형은 일부 T의 모음입니다. 'count'는 모음의 항목 수입니다. 컬렉션을 반복하고 obj에 대한 작업을 수행해야합니다.

감사합니다.

답변

19

반사는 한 번에 한 수준에서만 작동합니다.

속성에 색인하려고합니다. 잘못된 것입니다.

대신 색인을 생성해야하는 개체의 속성 값과 반환되는 개체 값을 읽으십시오. 여기

은 예입니다 :

using System; 
using System.Collections.Generic; 
using System.Reflection; 

namespace DemoApp 
{ 
    public class TestClass 
    { 
     public List<Int32> Values { get; private set; } 

     public TestClass() 
     { 
      Values = new List<Int32>(); 
      Values.Add(10); 
     } 
    } 

    class Program 
    { 
     static void Main() 
     { 
      TestClass tc = new TestClass(); 

      PropertyInfo pi1 = tc.GetType().GetProperty("Values"); 
      Object collection = pi1.GetValue(tc, null); 

      // note that there's no checking here that the object really 
      // is a collection and thus really has the attribute 
      String indexerName = ((DefaultMemberAttribute)collection.GetType() 
       .GetCustomAttributes(typeof(DefaultMemberAttribute), 
       true)[0]).MemberName; 
      PropertyInfo pi2 = collection.GetType().GetProperty(indexerName); 
      Object value = pi2.GetValue(collection, new Object[] { 0 }); 

      Console.Out.WriteLine("tc.Values[0]: " + value); 
      Console.In.ReadLine(); 
     } 
    } 
} 
+2

, 난, 응답에 대한 감사를 이해합니다. 이제는 작동하지만 아무도 모른다면 "Item"속성에 대해 알고 싶어합니다. – flesh

+0

답변을 찾았습니다. 특성은 속성이 아닌 클래스에있었습니다. 인덱서가없는 클래스에는 특성이 없습니다. –

+0

언급 - 나는 더 이상 나의 코드에서 수표를 확인한다. 업데이트 주셔서 감사합니다 :) – flesh

2

내가 이것을 볼 때까지 내가 거기에 대부분의 방법이었고, 나는 다른 곳을 보지 않았기 때문에 나는 이것을 게시하고; 열쇠는 GetValue (collection, new Object [] {i})를 사용하고있었습니다. 루프에서 GetValue (collection, new Object [i])를 사용하려고하지 않고; 루프 외부. (이 예에서는 "출력"을 무시할 수 있습니다.); 확인

private static string Recursive(object o) 
{ 
     string output=""; 
     Type t = o.GetType(); 
     if (t.GetProperty("Item") != null) 
     { 
      System.Reflection.PropertyInfo p = t.GetProperty("Item"); 
      int count = -1; 
      if (t.GetProperty("Count") != null && 
       t.GetProperty("Count").PropertyType == typeof(System.Int32)) 
      { 
       count = (int)t.GetProperty("Count").GetValue(o, null); 
      } 
      if (count > 0) 
      { 
       object[] index = new object[count]; 
       for (int i = 0; i < count; i++) 
       { 
        object val = p.GetValue(o, new object[] { i }); 
        output += RecursiveWorker(val, p, t); 
       } 
      } 
     } 
     return output;   
} 
0
Assembly zip_assembly = Assembly.LoadFrom(@"C:\Ionic.Zip.Reduced.dll"); 
Type ZipFileType = zip_assembly.GetType("Ionic.Zip.ZipFile"); 
Type ZipEntryType = zip_assembly.GetType("Ionic.Zip.ZipEntry"); 
string local_zip_file = @"C:\zipfile.zip"; 
object zip_file = ZipFileType.GetMethod("Read", new Type[] { typeof(string) }).Invoke(null, new object[] { local_zip_file }); 

// Entries is ICollection<ZipEntry> 
IEnumerable entries = (IEnumerable)ZipFileType.GetProperty("Entries").GetValue(zip_file, null); 
foreach (object entry in entries) 
{ 
    string file_name = (string)ZipEntryType.GetProperty("FileName").GetValue(entry, null); 
    Console.WriteLine(file_name); 
} 
관련 문제