[英]Web Service method - cannot be serialized because it does not have a parameterless constructor
[英]C# - Web Service still working despite using a class that does not have a parameterless constructor
我正在将汽车拍卖网站作为大学项目。 该网站使用网络服务来完成所有工作,并使我的生活更轻松,我使该类存储有关汽车的信息:
public class Car
{
private int id;
private string name;
private string desc;
private int startbid;
private DateTime closingdate;
public int Id
{
get
{
return id;
}
}
public string Name
{
get
{
return name;
}
}
public string Description
{
get
{
return desc;
}
}
public int StartBid
{
get
{
return startbid;
}
}
public DateTime ClosingDate
{
get
{
return closingdate;
}
}
public Car(int id, string name, string desc, int startbid, DateTime closingdate)
{
this.id = id;
this.name = name;
this.desc = desc;
this.startbid = startbid;
this.closingdate = closingdate;
}
}
每当我尝试在浏览器中查看.asmx时,都会出现一条错误消息,指出此类无法序列化,因为它没有无参数的构造函数,但是使用Car
类的所有内容在网站上仍然可以正常工作(例如,页面显示有关汽车的信息的所有内容均无例外)。 因此,Web服务仍在运行,并且以某种方式仍在对Car
类进行序列化。 这怎么可能?
编辑:我知道要使我的.asmx正确显示,我需要在类中添加public Car() {}
,但随后我还需要向每个属性添加set
方法,这并不是我真正想要做的,因为这些结果是从数据库中获取的,因此(在这种情况下)是只读的。 那么在这种情况下正确的解决方案是什么? 也许是Obsolete
属性或类似的东西?
可以绕过其构造函数分配类的实例:
var car = (Car)FormatterServices.GetUninitializedObject(typeof(Car));
但是,正如MSDN所说:
仅当用户打算立即填充所有字段时,才应将当前方法用于反序列化。
因此,我想这可能会使Web服务正常运行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.