c# - 如何将接口(interface)对象传递给 WebMethod?

标签 c# .net web-services oop interface

我有一个带有 web 方法的 .Net web 服务,该方法将 Interface 对象作为参数,每当我尝试访问该方法时,我都会收到异常提示:无法序列化成员 Product IProduct,因为它是一个接口(interface)。

有什么解决问题的建议吗??

[WebMethod]
Public double CalculateTotal(IProduct product, int Quantity)
{
  return product.Price * Quantity;
}

最佳答案

尝试向您的方法添加 XmlInclude 属性:

[WebMethod]
[XmlInclude(typeof(Product))]
Public double CalculateTotal(IProduct product, int Quantity)
{  
    return product.Price * Quantity;
}

编辑

以防万一您对我对“产品”类的使用感到困惑。将此类替换为程序集中实现 IProduct 的任何类,例如

[Serializable]
public class Product : IProduct
{
     public Product(string name, double price)
     {
         this.Name = name;
         this.Price = price;
     }

     public string Name { get; private set; }
     public double Price { get; private set; }
}

public interface IProduct
{
    string Name { get; }
    double Price { get; }
}

....

[Web Method]
[XmlInclude(typeof(Product))]
Public double CalculateTotal(IProduct product, int quantity)
{
     return product.Price * quantity;
}

基本上,当您将接口(interface)传递给 Web 服务时,它找不到任何模式,因此如果您使用 XmlInclude attribute并传入具体类,它将能够识别类型。

关于c# - 如何将接口(interface)对象传递给 WebMethod?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1496854/

相关文章:

c# - 带有参数的方法的异步等待问题

c# - 如何将两个 .cs 文件编译成单个 DLL?

c# - 如何绘制单个像素?

c# - Entity Framework 与.NET 4.0多对多关联

c# - RadioButton 点击​​另一个窗体

c# - 如何在Windows应用商店应用程序中获取图像的一个像素(C#)

java - 通过 JAX-RS 的 RESTful,@QueryParam 和@Consume 的常见用法是什么?

web-services - 在 REST 中处理添加/删除多对多关系的正确方法是什么?

JQuery/Ajax 返回成功消息并显示 Saved 指示器

c# - 是否可以触发 OnPropertyChanged 事件,而无需在 ViewModel 上的属性 setter 中显式调用它?