我在项目中使用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'。
我不应该投这个吗?如果没有,是否有解决方法?
答案 0 :(得分:12)
您不应该继承自WCF返回的代理类型。请考虑该类型不属于您!
您可以使用C#的分部类功能执行一些“扩展”,因为代理类是作为部分类生成的。不要使用ExtendedStore
属性创建类Id
,而是尝试:
public partial class Store
{
public int Id {get;set;}
}
这会向Store
类添加Id属性。您也可以这种方式添加方法事件等。
需要在包含服务引用的同一项目中定义partial类。
考虑具有根命名空间“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);
}
}
}
答案 1 :(得分:5)
检查数据合同KnownTypes它使您能够使用继承。 主要是让您能够将派生类的对象分配给父类的对象以及更多...检查KnownType和ServiceKnownType它将对您有所帮助。
答案 2 :(得分:2)
看起来你正试图做相同的事情:
BaseType client = new BaseType();
DerivedType store = (DerivedType) client.GetStore();
您正在转换为更加派生的类型,而不是转换为较小的派生类型。那永远不会奏效。