我正在调用单个Web服务的多种方法。对于每种方法,我都需要创建一个唯一的请求,并且每次都必须传递站点凭据和用户凭据,这是一项非常重复的任务。请找到以下代码。
ClientService.AddOrUpdateClientsRequest clientRequest = new ClientService.AddOrUpdateClientsRequest();
// Create and fill credentials
clientRequest.SourceCredentials = new ClientService.SourceCredentials();
clientRequest.SourceCredentials.SourceName = sourcename;
clientRequest.SourceCredentials.Password = password;
clientRequest.SourceCredentials.SiteIDs = siteIDs;
clientRequest.UserCredentials = new ClientService.UserCredentials();
clientRequest.UserCredentials.Username = "Siteowner";
clientRequest.UserCredentials.Password = "apitest1234";
clientRequest.UserCredentials.SiteIDs = siteIDs;
ClientService.AddOrUpdateClientsRequest updateClientRequest = new ClientService.AddOrUpdateClientsRequest();
// Create and fill credentials
updateClientRequest.SourceCredentials = new ClientService.SourceCredentials();
updateClientRequest.SourceCredentials.SourceName = sourcename;
updateClientRequest.SourceCredentials.Password = password;
updateClientRequest.SourceCredentials.SiteIDs = siteIDs;
updateClientRequest.UserCredentials = new ClientService.UserCredentials();
updateClientRequest.UserCredentials.Username = "Siteowner";
updateClientRequest.UserCredentials.Password = "apitest1234";
updateClientRequest.UserCredentials.SiteIDs = siteIDs;
ClientService.UploadClientDocumentRequest uploadRequest = new ClientService.UploadClientDocumentRequest();
//为UploadClientDocumentRequest对象分配凭据
如何创建通用函数以将值分配给相同的凭据字段但不同类型的对象。我正在考虑使用反射,但没有在线获得任何东西
答案 0 :(得分:2)
没有必要使用反射。 WCF代理类生成为partials,因此您可以创建一个接口以应用于包含这些属性的所有DTO:
$ python script.py tail /tmp/some.log --foo
usage: PROG [-h] [--foo] {status,tail} ...
PROG: error: unrecognized arguments: --foo
$ python script.py --foo tail /tmp/some.log
Namespace(command='tail', foo=True, path='/tmp/some.log')
然后在新文件或同一文件中,将此界面应用于所有这些DTO类:
public interface IAuthorizedRequest
{
SourceCredentials SourceCredentials { get; set; }
UserCredentials UserCredentials { get; set; }
}
然后,您可以创建一个将凭据应用于任何// Merely apply the interface, the other partial contains the properties
public partial class AddOrUpdateClientsRequest : IAuthorizedRequest { }
public partial class SomeOtherRequest : IAuthorizedRequest { }
的方法:
IAuthorizedRequest
然后像这样称呼它:
public void ApplyCredentials(IAuthorizedRequest request)
{
request.SourceCredentials = new ClientService.SourceCredentials();
request.SourceCredentials.SourceName = sourcename;
request.SourceCredentials.Password = password;
request.SourceCredentials.SiteIDs = siteIDs;
request.UserCredentials = new ClientService.UserCredentials();
request.UserCredentials.Username = "Siteowner";
request.UserCredentials.Password = "apitest1234";
request.UserCredentials.SiteIDs = siteIDs;
}