【问题标题】:Overloaded methods are not supported by WCF service?WCF 服务不支持重载方法?
【发布时间】:2013-03-07 10:05:25
【问题描述】:

我有两个名为

的方法
[OperationContract]
UserAccount GetUser(Int32 id);

[OperationContract]
UserAccount GetUser(string username, string password);

当我尝试构建它们时,他们说您不能在服务中使用同名方法?是吗。

【问题讨论】:

  • 注意:Polymorphism 与重载不同。此外,请在问题中包含确切错误消息,因为它使它们更易于搜索(如果有人搜索所述错误消息)。
  • 重载是多态的一种实现。多态是一个抽象的概念。
  • 重载与多态正交,并且存在于一些不支持[subtype]多态的语言中。在某些支持 [subtype] 多态性的语言中也没有重载。覆盖通常与 [subtype] 多态性相关,但我离题了..
  • 重载是实现多态性的实用方法,我相信......无论如何它有两种方式到达一个目的地:p
  • 没有。 Overloading 与多态性有关:“方法重载不应与 [..] 多态性混淆在运行时选择正确的方法,例如通过虚函数,而不是静态的。”

标签: wcf overloading


【解决方案1】:

这是 WSDL 的限制。它不支持与 C#/.NET 相同的重载概念,因此服务上的方法名称必须是唯一的。您有两种选择来解决您的问题。

第一个是为您的方法使用不同的名称。另一种方法是在您的一个 OperationContracts 上设置 Name 属性,如下所示

[OperationContract(Name="GetUserById")]
UserAccount GetUser(Int32 id);

[OperationContract]
UserAccount GetUser(string username, string password);

【讨论】:

  • gr8 谢谢...所以现在我将其识别为 GetUserById 或 GetUser,我是 ryt
  • @Arun 该名称用于 WCF 服务的 WSDL 描述。如果您使用普通的 WCF 客户端,它应该提供您在接口上定义的重载方法
【解决方案2】:

WSDL 不支持与 c# 相同的重载概念。您可以在 OperationContract 中使用 Name 来指定您的方法

 [OperationContract(Name="GetUserInt")]
 UserAccount GetUser(Int32 id);

 [OperationContract(Name="GetUserString")]
 UserAccount GetUser(string username, string password);

【讨论】:

    【解决方案3】:

    试试这个:

    - [OperationContract(Name= "GetUserWithID")]
       UserAccount GetUser(Int32 id);
    
    - [OperationContract(Name= "GetUserWithUserName")]
      UserAccount GetUser(string username, string password);
    

    More Info

    【讨论】:

      【解决方案4】:

      这是 WCF 的缺点。这背后的原因是当我们为客户端依赖服务时,不应该有重复,否则客户端会混淆哪个方法在做什么?因此,这里有解决问题的选项。通过使用Operation Contract的不同name属性。

      [OperationContract(Name="GetUserByID")]

      UserAccount GetUser(Int32 id);

      [OperationContract(Name="GetUserByUName_Password")]

      UserAccount GetUser(字符串用户名,字符串密码);

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-09-08
        • 1970-01-01
        • 1970-01-01
        • 2015-09-15
        • 2011-11-06
        相关资源
        最近更新 更多