【问题标题】:Error when calling Polymorphic method on WCF Client在 WCF 客户端上调用多态方法时出错
【发布时间】:2014-04-30 00:42:43
【问题描述】:

此错误是This 上一个问题的结果。我正在尝试从 WCF 客户端调用多态方法。这是我的合同:

public interface IOhmioService
{        
  [OperationContract]
  IEnumerable<Enumerador> GetEnumerador<T>() where T : IEnumerador, new();        
}

这是我的类实现:

public class OhmioService : IOhmioService
{
  public IEnumerable<Enumerador> GetEnumerador<T>() where T : IEnumerador, new()
  {
      T _obj = new T();
      return _obj.Enumerar();  
  }
}

并像这样从客户端调用它:

public IEnumerable<Enumerador> Clients { get; set; } 
Clients = this.serviceClient.GetEnumerador<Clientes>();

如果我从类中调用此方法,一切正常。但是,如果我从 WCF 客户端调用它,则会出现此错误:

非通用方法'Ohmio.Client.OhmioService.OhmioServiceClient.GetEnumerador()' 不能与类型参数一起使用

我做错了什么?谢谢!

更新

好的。我尝试了建议的解决方案,并得到了这个可怕的错误:

类型“System.RuntimeType”未指定为合约名称 RuntimeType:http://schemas.datacontract.org/2004/07/System'。尝试使用 DataContractResolver 或将未知类型静态添加到已知类型列表中(例如,使用属性 KnownTypeAttribute 或将它们添加到已知类型列表中以传递给 DataContractSerializer)

也许在 wcf 上使用泛型类型毕竟不是一个好主意。我试图减少 WCF 服务上的重复代码。

【问题讨论】:

  • 这个多态性如何?它不是虚拟的。
  • 对不起@The Mouth of a Cow,也许我在这里有点困惑。我认为这是多态的,因为它根据期望类型在多个对象上调用通用方法。仍然知道为什么会出现此错误?
  • 多态是虚方法的同义词:它意味着根据对象的真实类型而不是编译时间来决定在运行时调用哪个方法。您上面拥有的是一个完全编译时的构造。我在下面为您提出了解决方案。

标签: c# wcf


【解决方案1】:

在 WCF ServiceContract 中不能有通用的 OperationContract 方法。更多详情请看这里:WCF. Service generic methods

您需要将类型作为方法参数传递:

public interface IOhmioService
{        
  [OperationContract]
  IEnumerable<Enumerador> GetEnumerador(string typeName);       
}

public class OhmioService : IOhmioService
{
  public IEnumerable<Enumerador> GetEnumerador(string typeName)
  {
      var type = Type.GetType(typeName);
      var _obj = (IEnumerador)Activator.CreateInstance(type);
      return _obj.Enumerar();  
  }
}

更新

见上面的更新;传递类型的完全限定名称。这不会导致序列化问题。

【讨论】:

  • 好的,我试试这个,但是会遇到一个可怕的错误,我会将其翻译为原始问题的更新。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多