反射GetValue给出了一个TargetException(非静态方法需要一个目标)

Eri*_*ker 2 c# reflection singleton invoke

我有一个webservice控制器,它具有公共静态属性,这是webservices.我使用反射来调用这些web服务上的方法.

当所有webservice属性都是静态的时,根本没有问题.这很适合使用反射调用webservicecontroller中的方法:

Type wsControllerType = typeof(wsController);
PropertyInfo WebserviceProperty = wsControllerType.GetProperty(wsName, Some bindingflags);
MethodInfo method = WebserviceProperty.PropertyType.GetMethod(methodname);
method.Invoke(WebserviceProperty.GetValue(null, null), parameters);
Run Code Online (Sandbox Code Playgroud)

webservicecontroller将转换为单例,因此将删除静态Web服务属性.

当我尝试通过反射调用方法时,我在最后一部分得到了一个TargetException(WebserviceController.GetValue(null,null).

我尝试过多种方法,但无法让它发挥作用.我想我错过了一些简单的事情......谁可以提供帮助?

Jar*_*Par 6

为了通过反射调用实例属性,您需要提供一个实例来处理.提到的帖子WebServiceProperty已经变成单身,所以只需使用单例值

WebserviceProperty.GetValue(wsController.GetTheSingleton(), null)
Run Code Online (Sandbox Code Playgroud)

虽然我必须说在这里做反思似乎有点奇怪.您可以访问该wsController类型,因此您应该能够静态绑定到其所有成员.为什么不在这里使用正常的非反射?