泛型程序,从客户端访问WCF服务
问题描述:
请看下面的代码,其中一个客户端访问WCF服务泛型程序,从客户端访问WCF服务
功能GetPriority
public List<Priority> GetPriority()
{
List<Priority> lstPriority = new List<Priority>();
using (TmsServiceClient client = new TmsServiceClient())
{
try
{
lstPriority = client.GetPriority();
}
catch (FaultException<TMSCustomException> myFault)
{
Console.WriteLine(myFault.Detail.ExceptionMessage);
client.Abort();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
client.Abort();
}
}
return lstPriority;
}
功能的getStatus:
public List<Status> GetStatus()
{
List<Status> lstStatus = new List<Status>();
using (TmsServiceClient client = new TmsServiceClient())
{
try
{
lstStatus = client.GetStatus();
}
catch (FaultException<TMSCustomException> myFault)
{
Console.WriteLine(myFault.Detail.ExceptionMessage);
client.Abort();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
client.Abort();
}
}
return lstStatus;
}
这两种方法都工作正常。可以看出,这两种方法之间有许多相似之处,它们仅在方法调用和返回类型时才有所不同。这可以使通用?如果是这样怎么办?或者任何其他更好的方式,以便捕获异常块代码不应该每次重复。
在此先感谢
答
您可以轻松地重构几乎整个Get ...
方法为普通之一。唯一真正的可变部分是调用哪个客户端方法,可以使用Func<T,TResult>
轻松解决。
private List<T> Get<T>(Func<TmsServiceClient, List<T>> clientCall)
{
List<T> results = new List<T>();
using (TmsServiceClient client = new TmsServiceClient())
{
try
{
// invoke client method passed as method parameter
results = clientCall(client);
}
catch (FaultException<TMSCustomException> myFault)
{
Console.WriteLine(myFault.Detail.ExceptionMessage);
client.Abort();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
client.Abort();
}
}
return results;
}
现在你的方法实现这个样子:
public List<Status> GetStatus()
{
return Get<Status>(client => client.GetStatus());
}
public List<Priority> GetPriority()
{
return Get<Priority>(client => client.GetPriority());
}
编辑回应OP评论:
Func<TmsServiceClient, List<T>>
作为参数传递给Get<T>
方法是delegate。委托是一种函数指针 - 一个对象,用于代理稍后要执行的一些动作(因此名称)。
Func<TmsServiceClient, List<T>>
基本上是一个代表,它接受一个输入参数(的TmsServiceClient
类型)并返回List<T>
作为结果。
现在,我们在做什么例如GetStatus
?我们创造这样的委托实例(通过lambda expression) - 我们“告诉”它来执行GetStatus()
方法上Client
对象,我们将提供:
// this line works the same as in example above
// Take client as parameter call its .GetStatus method
return Get<Status>((TmsServiceClient client) => client.GetStatus());
而这正是发生在
// invoke client method passed as method parameter
results = clientCall(client);
一行。代表执行我们要求的方法。
我无法理解部分Func
user1025901
2012-01-12 07:36:29
@ user1025901:'Func>'是一个代表 - 请检查我的编辑。 –
2012-01-12 20:02:01