我上过这堂课:
class UrlManagementServiceClient : System.ServiceModel.ClientBase<IUrlManagementService>, IUrlManagementService
ClientBase实现IDisposable
和ICommunicationObject
。我也有这个界面:
interface IUrlManagementProxy : IUrlManagementService, ICommunicationObject, IDisposable
但是我无法将UrlManagementServiceClient
个对象投射到IUrlManagementProxy
。有没有办法实现这个目标?我想最终得到一个可以访问所有三个接口上所有方法的对象。
答案 0 :(得分:4)
您只能转换为您继承的接口,以便能够转换为您需要实现该接口的IUrlManagementProxy
。
class UrlManagementServiceClient :
System.ServiceModel.ClientBase<IUrlManagementService>, IUrlManagementProxy
然后,您可以将UrlManagementServiceClient
投射到UrlManagementProxy
,IUrlManagementService
,ICommunicationObject
或IDisposable
。
修改强>
WCF生成的类是部分的,这意味着您可以在另一个文件中扩展类定义。把
public partial class UrlManagementServiceClient : IUrlManagementProxy {}
在另一个代码文件中,您的课程也会实现完整的IUrlManagementProxy
界面,然后您可以将其转换为IUrlManagementProxy
。
答案 1 :(得分:1)
UrlManagementServiceClient
实施IUrlManagementProxy
而不是IUrlManagementService
class UrlManagementServiceClient : System.ServiceModel.ClientBase<IUrlManagementProxy>, IUrlManagementProxy
答案 2 :(得分:0)
您需要在IUrlManagementProxy
上实施UrlManagementServiceClient
。没有其他办法 - 它是单独的类型。
答案 3 :(得分:0)
您显然无法将对象强制转换为未实现的接口。
但是,你能做什么(如果从UrlManagementServiceClient
实例中为每个接口实现所有方法是有意义的话)是换行你的UrlManagementServiceClient
在实现所需接口的对象中。
这称为Decorator pattern(而不是代理)。代理通常“显示”为底层对象,而在这种情况下,您正在添加客户端没有的功能。
换句话说,你需要一个新的课程:
public class UrlManagementClientProxy : IUrlManagementProxy
{
// we need a reference to the underlying client
private readonly UrlManagementServiceClient _client;
// underlying client is passed to the proxy in constructor
public UrlManagementClientProxy(UrlManagementServiceClient client)
{
_client = client;
}
#region IUrlManagementProxy methods
// you implementation goes here. if the underlying client
// already implements a certain method, then you just need
// to pass the call
// for example, client already implements methods
// from the IUrlManagementService interface, so use them
public string GetUrl() // made up
{
return _client.GetUrl();
}
#endregion
}
这允许您重用客户端的实现,并在其上添加其他功能。
答案 4 :(得分:0)
为了解决这个问题,我只是扩展了类并在其上声明了聚合接口:
public class UrlManagementProxy : UrlManagementServiceClient, IUrlManagementProxy
{
public UrlManagementProxy(Binding binding, EndpointAddress remoteAddress)
: base(binding, remoteAddress)
{
}
}
然后我使用UrlManagementProxy
代替UrlManagementServiceClient
。
我只需要传递我需要的构造函数。所有其余的都是自动处理的。另外这种方式我不需要修改UrlManagementServiceClient
,所以我可以重新生成它,一切都会工作。