我有一个带有 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/