简体   繁体   English

反映通用方法不起作用

[英]Reflection of generic method not working

I have a generic static method which registers a interface and I need to write that using c# reflection. 我有一个注册接口的通用静态方法,我需要使用c#反射将其编写。

Services.AddService<ITBroker>(new TBrokerService());

I tried following code but it is not working 我尝试了以下代码,但无法正常工作

Type[] externTBrokerService = Assembly.LoadFrom("Business.dll").GetTypes();
Type[] externService = Assembly.LoadFrom("ServiceModel.dll").GetTypes();
Type iTBroker = externITBroker[12];
MethodInfo method = externService[1].GetMethods()[2];
//Gets Add Service method
MethodInfo generic = method.MakeGenericMethod(iTBroker);
//Make method generic           
generic.Invoke(null,new object[] { externTBrokerService[0]});
//invoke the service

Above code gives me very generic exception of parameters. 上面的代码为我提供了非常通用的参数例外。

What is the write way to write reflection for above code? 上面的代码写反射的写方法是什么?

As it was in comments: 就像在评论中一样:

Note that externTBrokerService[0] is a Type and not an instance of that type. 请注意, externTBrokerService[0]是一种Type而不是该类型的实例。

Having that I feel a need to include sense of other comments as part of my answer. 有鉴于此,我感到有必要在回答中包括其他意见。

Type iTBroker = externITBroker[12];

this is wrong! 这是错的! And sooner or later this will fail to find your type as the order of types in this collection is undetermined and can change. 迟早将无法找到您的类型,因为此集合中类型的顺序不确定,并且可以更改。 You should do it like this: 您应该这样做:

Type iTBroker = externITBroker.Single(x => x.Name == "ITBroker");

This is far form foolproof so be sure that the condition gives you unique result. 这远非万无一失,因此请确保条件能给您带来独特的效果。

or simply load that type directly by (assuming that this is the AssemblyQualifiedName of your type): 或直接通过以下方式直接加载该类型(假设这是您类型的AssemblyQualifiedName):

Type.GetType("Business.ITBroker, Business");

To find method on your type there is a method Type.GetMethod one of its overloads will be sufficient to find your method. 要在您的类型上查找方法,可以使用方法Type.GetMethod的重载之一就可以找到您的方法。

To create instance of your type that needs to be passed as argument you can use 要创建需要作为参数传递的类型的实例,可以使用

Activator.CreateInstance(brokerServiceType);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM