我在掌握C#的反射方面有困难,所以我要把我的具体情况写下来,看看你们能拿出什么来。我在这里读过大量的C#反射问题,但我还是不明白。
这是我的情况,我试图访问一个数组,它是我可以访问的类的非公共成员。
基本上,它是一个System.Collections.CollectionBase,它有一个名为"list“的数组变量,但是它有这种父类型的OrderCollection,它的反射就是把我搞糊涂了。
我必须做很多这些,所以一个好的指南或例子将真正有帮助。如果你想要更多的信息,请告诉我。
我抹黑了名称空间的名称,并不是因为我所做的并不是非法的,而是我试图在这个问题上率先上市,所以我要小心。
发布于 2010-09-23 13:43:43
您试图使用什么反射呢?CollectionBase
支持索引,但只能通过IList
的显式接口实现来实现,因此您应该能够编写:
IList list = Acct.Orders;
response = list[0];
您可能需要将结果转换为更合适的类型,但我认为这里不需要反射。
编辑:原始答案没有考虑到显式接口实现。
发布于 2016-11-10 22:09:02
虽然这可能对你没有帮助,但它可能会帮助别人。下面是一个简化的反射示例:
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();
}
}
}
https://stackoverflow.com/questions/3778951
复制相似问题