【发布时间】:2013-06-19 01:13:45
【问题描述】:
我不确定如何最好地描述我想要的东西,所以我将从高层次开始,然后回顾我对实施的想法。
使用 c# 我正在尝试创建一个具有通用返回类型的方法,并将服务引用中的方法作为参数。
这个通用方法将新建服务引用,调用我传入的服务引用的方法,执行服务引用所需的所有错误处理和检查,然后关闭或中止它并返回结果来电。
这样的伪代码:
public T CallServiceReference<T>(method serviceRefMethod) {
T result = null;
ServiceReference svcClient = new ServiceReference.Client();
try {
result = svcClient.serviceRefMethod;
svcClient.Close();
} catch (ExceptionType ex) {
// log error message
svcClient.Abort();
throw;
}
return result;
}
这在 C# 中可能吗?我正在寻找泛型和代表。我的主要问题之一是在没有实例化服务引用的情况下将服务引用的方法委托给一个。如果我必须实例化服务引用,我想我还不如为每个方法调用放置所有的关闭、中止和错误处理。
我正在研究不同的设计模式,虽然有点困难,因为我不知道我正在寻找的设计模式的名称,也不知道它是否存在。
如果我可以提供任何其他信息或澄清,请告诉我。
更新(第 2 部分): 现在我正在尝试使用它调用的方法创建一个封装变量的委托。
public delegate T Del<T>();
public static IEnumerable<String> GetDataFromService(String username) {
ServiceReference.ServiceClient client = new ServiceReference.ServiceClient();
// the method I'm going to call returns a string array
Del<String[]> safeClientCall = new Del<String[]>(client.DataCall);
// the above call is what I need to use so the C# compiles, but I want to do this
// the below code throws an error...
Del<String[]> safeClientCall = new Del<String[]>(client.DataCall(username));
var result = DataCallHandlerMethod(ref client, safeClientCall);
return result;
}
基本上从我的调用方法传递用户名参数,并且该用户名参数已经定义。我不想在调用委托时定义它。有没有办法使用 c# 来做到这一点?
【问题讨论】:
-
我已经编辑了你的标题。请参阅“Should questions include “tags” in their titles?”,其中的共识是“不,他们不应该”。
-
你的方法需要使用反射你可以在你的代码中使用反射吗
-
我可以在我的代码中使用反射,但是我在调用站点新建服务引用并将引用连同方法的委托及其参数一起传递给它的解决方案似乎就像它会工作一样。
标签: c# design-patterns generics delegates service-reference