Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on May 16th, 2012  |  syntax: None  |  size: 1.42 KB  |  hits: 17  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. Reflection - how to get value at specified index of parameter
  2. public class NumberCollection : List<int>
  3. {
  4.     public NumberCollection()
  5.     {
  6.         nums = new List<int>();
  7.         nums.Add(10);
  8.     }
  9.  
  10.     public new int this[int i]
  11.     {
  12.         get { return (int) nums[i]; }
  13.     }
  14.  
  15.     private List<int> nums;
  16.  
  17. }
  18.  
  19. public class TestClass
  20. {
  21.     public NumberCollection Values { get; private set; }
  22.  
  23.     public TestClass()
  24.     {
  25.         Values = new NumberCollection();
  26.         Values.Add(23);
  27.     }
  28. }
  29.  
  30.  
  31. class Program
  32. {
  33.     static void Main(string[] args)
  34.     {
  35.         TestClass tc = new TestClass();
  36.  
  37.         PropertyInfo pi1 = tc.GetType().GetProperty("Values");
  38.         Object collection = pi1.GetValue(tc, null);
  39.  
  40.         // note that there's no checking here that the object really
  41.         // is a collection and thus really has the attribute
  42.         String indexerName = ((DefaultMemberAttribute)collection.GetType()
  43.             .GetCustomAttributes(typeof(DefaultMemberAttribute),
  44.                 true)[0]).MemberName;
  45.         // Code will ERROR on the next line...
  46.         PropertyInfo pi2 = collection.GetType().GetProperty(indexerName);
  47.         Object value = pi2.GetValue(collection, new Object[] { 0 });
  48.  
  49.         Console.Out.WriteLine("tc.Values[0]: " + value);
  50.         Console.In.ReadLine();
  51.     }
  52. }
  53.        
  54. var prop = Type.GetProperties()
  55.                .Where(prop => prop.DeclaringType == collection.GetType())
  56.                .First();