[英]Expose interface methods names
I'm working in a method that invoke a class method using reflection and getting my service object class from spring. 我正在研究一种使用反射调用类方法并从Spring获取我的服务对象类的方法。 Something like this:
像这样:
private void InvokeMethod(string serviceName, string methodName, params object[] arguments)
{
object service = SpringContextManager.Instance.GetObject(serviceName);
Type classType = service.GetType();
MethodInfo method = classType.GetMethod(methodName);
method.Invoke(service, arguments);
}
//...
InvokeMethod(SpringObjectsConstants.LogDocumentService, "SetDocumentStatus", 9127, LogDocumentPendingStatusEnum.Finalized)
I need to inform the method name as a string so the method can call it, but I dont want to work with strings because if the method name changes, I can´t track the usages of it. 我需要以字符串形式通知方法名称,以便该方法可以调用它,但是我不想使用字符串,因为如果方法名称更改,我将无法跟踪其用法。 There is any way to work with the interfaces methods that look like an enum or something?
有什么方法可以像枚举之类的接口方法一起工作? Anything that could cause compilation errors or I can update renaming the method name in visual studio?
有什么可能导致编译错误的问题,或者我可以在Visual Studio中更新重命名方法名称的方法吗?
There is a refactoring-safe way: You can use an expression and parse that. 有一种重构安全的方法:您可以使用表达式并对其进行解析。 The idea is the same as in this article .
这个想法与本文相同。
Unfortunately, it gets a bit messy when you use methods instead of properties, because you need to pass the arguments to the method. 不幸的是,当您使用方法而不是属性时,它会变得有些混乱,因为您需要将参数传递给方法。
Having said that, there is a much more elegant solution. 话虽如此,还有一个更优雅的解决方案。 It simply uses a delegate
它只是使用一个委托
However, I don't really see the need for reflection here at all. 但是,我根本没有真正需要反思的地方。 You can simply pass a delegate:
您可以简单地传递一个委托:
InvokeMethod<ServiceImpl>(
SpringObjectsConstants.LogDocumentService,
x => x.SetDocumentStatus(9127, LogDocumentPendingStatusEnum.Finalized));
This would have another advantage: If you changed the type of a parameter or added or removed a parameter from the method, you also would get a compilation error. 这将具有另一个优点:如果更改了参数的类型或从方法中添加或删除了参数,您还将收到编译错误。
InvokeMethod
would look like this: InvokeMethod
将如下所示:
private void InvokeMethod<TService>(
string serviceName, Action<TService> method)
{
TService service = (TService)SpringContextManager.Instance
.GetObject(serviceName);
method(serviceName);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.