2010-09-23 75 views
3

我很難在C#中掌握反思,所以我會把我的具體情況放下來,看看你們能想出什麼。我已經閱讀了C#反射問題的TONS,但我仍然只是不明白。C#反思方法?

所以這是我的情況;我試圖訪問一個數組,該數組是我可以訪問的類的非公共成員。

alt text

基本上這是一個System.Collections.CollectionBase其具有所謂的「列表」的數組變量,但它有OrderCollection的該父類型和它的反射只是混淆的地獄我的。

我必須做很多這些,所以一個好的指導或例子才能真正幫助。如果您想了解更多信息,請告訴我。

我把命名空間的名字弄糊塗了,並不是因爲我所做的不是非法的,而是我試圖首先在這個市場上進行銷售,所以我試圖小心。

+2

不要用魔法來駕駛汽車。又名不要讓它比現在更復雜。反思很複雜。好的設計更好。 – Dykam 2010-09-23 13:45:52

回答

9

你想用什麼反射? CollectionBase支持索引,但只能通過IList的顯式接口實現,所以你應該能夠編寫:

IList list = Acct.Orders; 
response = list[0]; 

您可能需要將結果轉換爲更合適的類型,但我沒有看到任何這裏需要反思。

編輯:原始答案沒有考慮明確的接口實現。

+0

喬恩,我見過你回答幾乎每個反射問題,我在StackOverflow上查找這裏。在這裏你來拯救。要回答你的問題,我不知道我爲什麼認爲我需要這個,我猜想我認爲它應該更難。我對C#很陌生,所以我在這裏很難說出口。不過,你絕對正確,不需要反思。 – 2010-09-23 13:47:39

+0

@Zach:沒問題。 「你不需要使用反射」是關於我可以給一個反射問題的最令人愉快的答案 - 它是可用的,但是當你不需要它時更好。 – 2010-09-23 13:59:12

0

雖然這可能不會幫助你,但它可能會幫助其他人。下面是一個簡單的反射示例:

using System; 
using System.Reflection; 


namespace TeamActivity 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      // Dynamically load assembly from the provided DLL file. 
      Assembly CustomerAssembly = Assembly.LoadFrom("BasicCalculations.dll"); 
      // Get a Type from the Assembly 
      Type runtimeType = CustomerAssembly.GetType("BasicCalcuation.BasicCalc"); 
      // Get all methods from the Type. 
      MethodInfo[] methods = runtimeType.GetMethods(); 

      // Loop through all discovered methods. 
      foreach (MethodInfo method in methods) 
      { 
       Console.WriteLine("Method name: " + method.Name); 
       // Create an array of parameters from this method. 
       ParameterInfo[] parameters = method.GetParameters(); 
       // Loop through every parameter. 
       foreach (ParameterInfo paramInfo in parameters) 
       { 
        Console.WriteLine("\tParamter name: " + paramInfo.Name); 
        Console.WriteLine("\tParamter type: " + paramInfo.ParameterType); 
       } 
       Console.WriteLine("\tMethod return parameter: " + method.ReturnParameter); 
       Console.WriteLine("\tMethod return type: " + method.ReturnType); 
       Console.WriteLine("\n"); 
      } 
      // Invoke the Type that we got from the DLL. 
      object Tobj = Activator.CreateInstance(runtimeType); 
      // Create an array of numbers to pass to a method from that invokation. 
      object[] inNums = new object[] { 2, 4 }; 
      // Invoke the 'Add' method from that Type invokation and store the return value. 
      int outNum = (int)runtimeType.InvokeMember("Add", BindingFlags.InvokeMethod, null, Tobj, inNums); 
      // Display the return value. 
      Console.WriteLine("Output from 'Add': " + outNum); 

      Console.WriteLine("\nPress any key to exit."); 
      Console.ReadKey(); 
     } 
    } 
}