2010-05-20 87 views
2

我在我的项目中使用WCF服务。该服务返回一个名为“Store”的类。我创建了一个从“Store”继承的新的本地类。我的班级被称为“ExtendedStore”。 我ExtendedStore看起来是这样的:如何正确地扩展WCF返回的类?

class ExtendedStore : StoreManagerService.Store 
{ 
    public int Id; 
    .... 
} 

现在我使用的WCF服务的内容投射到我的课用下面的代码:

StoreManagerService.StoreClient client = new StoreManagerService.StoreClient(); 
ExtendedStore store = (ExtendedStore) client.GetStore(); // bombs here 

我无法从投返回的存储类服务到我的ExtendedStore类。 我得到以下错误信息:

无法转换 类型的对象ConsoleApplication1.StoreManagerService.Store“ 键入 “ConsoleApplication1.ExtendedStore”。

我不应该能够施放它吗?如果没有,是否有解决方法?

回答

11

您不应该从WCF返回的代理类型继承。考虑到这种类型不属于你!

您可以使用C#的部分类功能来做一些“扩展”,因为代理类是作为部分类生成的。相反,与Id财产创造ExtendedStore类的,请尝试:

public partial class Store 
{ 
    public int Id {get;set;} 
} 

这增加了id属性为Store类。您也可以以这种方式添加方法事件等。

部分类将需要在包含服务引用的同一个项目中定义。


考虑一个具有根名称空间“Project”的项目。对于返回“Store”对象的Web服务,您有一个名为“Commerce”的服务引用。这意味着,有一个名为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 
    } 
} 

您将命名为“商务”项目根目录下创建一个文件夹。这样你创建的类的命名空间将会是“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); 
     } 
    } 
} 
+0

可能是最简单的解决方案,如果他实际上正在生成代理。我觉得你有一个继承问题有点奇怪,但是不能通过部分类机制来扩展类。不从班级继承的原因也适用于以这种方式扩展,即imo。 – Thorarin 2010-05-20 18:58:13

+0

现在我将如何使用这个部分课程? – vikasde 2010-05-20 19:02:06

+0

感谢您的帮助。 – vikasde 2010-05-20 19:52:43

5

检查数据合同KnownTypes它使您能够使用继承。 主要为您提供将派生类的对象分配给父类的对象以及更多...检查KnownType和ServiceKnownType它会帮助您。

+2

另见http://stackoverflow.com/questions/560218/wcf-configuring-known-types如何做到这一点纯粹的App.config配置。如果您无法更改“StoreManagerService.Store”或在服务合同中提供“ServiceKnownType”,这将是必需的。 – Thorarin 2010-05-20 18:45:27

2

它看起来就像你正在试图做的相当于:

BaseType client = new BaseType(); 
DerivedType store = (DerivedType) client.GetStore(); 

你转换成更多的派生类型,而不是在较小的派生类型。那绝对不行。

+0

哦......没想到。谢谢:/ – vikasde 2010-05-20 18:40:28

+0

@Thorarin:他的例子永远不会工作。实际上,这是客户端返回Store的一个例子,而不是'ExtendedStore'。在OP的情况下,该服务永远不会返回'ExtendedStore'。 – 2010-05-20 18:47:42

+0

@John Saunders:看起来很可能来自代码的故事,但没有任何代码能够真正显示它返回的内容:) – Thorarin 2010-05-20 18:49:34