我在我的项目中使用 WCF 服务。该服务返回一个名为“Store”的类。我创建了一个继承自“Store”的新本地类。我的课程名为“ExtendedStore”。
我的 ExtendedStore 看起来像这样:
class ExtendedStore : StoreManagerService.Store
{
public int Id;
....
}
现在我使用 WCF 服务通过以下代码转换为我的类:
StoreManagerService.StoreClient client = new StoreManagerService.StoreClient();
ExtendedStore store = (ExtendedStore) client.GetStore(); // bombs here
我无法将返回的 Store 类从服务转换为我的 ExtendedStore 类。
我收到以下错误消息:
无法转换类型的对象
'ConsoleApplication1.StoreManagerService.Store'
输入
'ConsoleApplication1.ExtendedStore'。
难道我就不能投吗?如果没有,有解决方法吗?
您不应继承自 WCF 返回的代理类型。考虑一下该类型不属于您!
您可以使用 C# 的分部类功能进行一些“扩展”,因为代理类是作为分部类生成的。而不是创建类ExtendedStore
与Id
属性,尝试:
public partial class Store
{
public int Id {get;set;}
}
这会向Store
班级。您还可以通过这种方式添加方法事件等。
需要在包含服务引用的同一项目中定义分部类。
考虑一个具有根命名空间“Project”的项目。您有一个名为“Commerce”的服务引用,指向返回“Store”对象的 Web 服务。这意味着有一个名为Project.Commerce.Store
:
// Proxy code generated by "Add Service Reference":
namespace Project.Commerce {
[DataContract]
public partial class Store {
[DataMember]
public string StoreName {get;set;}
// More data members here
}
}
您将在项目根目录下创建一个名为“Commerce”的文件夹。这样您创建的类的名称空间将是“Project.Commerce”。然后创建您的部分类:
// This is your code in Store.cs in the new "Commerce" folder:
namespace Project.Commerce {
public partial class Store {
public int Id {get;set;}
public override string ToString() {
return String.Format("Store #{0}: {1}", Id, StoreName);
}
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)