gpt4 book ai didi

c# - ASMX Web 服务未序列化抽象基类

转载 作者:太空狗 更新时间:2023-10-29 17:50:11 24 4
gpt4 key购买 nike

我有一个抽象类。让我们称之为Lifeform。它看起来像:

public abstract class Lifeform {
public virtual int Legs { get; set; }
public virtual int Arms { get; set; }
public virtual bool Alive { get; set; }
}

(虚拟属性是因为我使用的是 nHibernate,如果它们不是虚拟属性,它就会发牢骚。)

然后我有一个继承自该 Lifeform 类的类;我们称之为人类。它看起来像:

public class Human: Lifeform {
public virtual bool Hat { get; set; }
public virtual int Age { get; set; }
public virtual string Name { get; set; }
}

一切都很美好,我可以使用我的类,当我使用它时,Human 会获得 Legs、Arms 和 Alive 属性。除了,也就是说,当我尝试使用 Human 类创建 Web 服务时。序列化对象为我提供了 Hat、Age 和 Name,但没有 Legs、Arms 或 Alive 属性。

我见过建议使用的解决方法

[System.Xml.Serialization.XmlInclude(typeof(Human))]

在基类 (Lifeform) 上,但这似乎是违反 OO 的可怕 hack。将基类链接到继承它的类?呃。

有没有人遇到过这个具体问题?有什么想法吗?如果更深入的示例有助于描述我正在做的更多事情,我将提供更多代码。

最佳答案

根据我的阅读,您可以在返回对象的 Web 方法中包含 XMLInclude 属性,而不是在基类中。仍然不漂亮,但可能比将派生类名称放在基类中更能吸引您。我还没有尝试过,但我认为你可以做这样的事情。

[WebMethod]
[XmlInclude(typeof(LifeForm))]
public Human GetHuman()
{
return new Human();
}

关于c# - ASMX Web 服务未序列化抽象基类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1262246/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com