我在C#中抓住反思时遇到了麻烦,所以我将把我的具体情况放下来,看看你们能想出什么。我已经在这里阅读了TONS的C#反思问题,但我仍然只是没有得到它。
所以这是我的情况;我正在尝试访问一个数组,该数组是我有权访问的类的非公共成员。
基本上它是一个 System.Collections.CollectionBase ,它有一个名为“list”的数组变量,但它的父类型为 OrderCollection ,它的反映就是让我感到困惑。
我必须做很多这些,所以一个好的指南或例子真的会有所帮助。如果您想了解更多信息,请与我们联系。
我将命名空间的名称涂黑了不是因为我所做的事情无论如何都不是非法的,但我正试图率先推销这个,所以我要小心。
答案 0 :(得分:9)
你想用反射做什么? CollectionBase
支持索引,但只能通过IList
的显式接口实现,所以你应该能够编写:
IList list = Acct.Orders;
response = list[0];
您可能需要将结果转换为更合适的类型,但我认为此处不需要反射。
编辑:原始答案未考虑显式接口实现。
答案 1 :(得分: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();
}
}
}