Dav*_*nde 8 c# attributes xml-serialization
假设我有以下(简单的简单)基类:
public class Simple
{
public string Value { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
我现在想要做以下事情:
public class PathValue : Simple
{
[XmlAttribute("path")]
public string Value { get; set; }
}
public class ObjectValue : Simple
{
[XmlAttribute("object")]
public string Value { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
但实际上没有重新定义财产.我想将属性应用于基类的成员.这可能吗?
真正的问题是,在我从/到XML的序列化机制(它工作得非常出色),我发现很多类似的元素只有属性的名称不同(它们不一致,我不控制格式).现在我需要为每个这样的元素创建一个不同的类,而它们就像100%相同(除了属性).
我不认为这是可能的,但你可能永远不会知道.
更新:
我试过Marc的方法,但无济于事:
public class Document
{
public PathValue Path;
public ObjectValue Object;
}
class Program
{
static void Main(string[] args)
{
var doc = new Document()
{
Path = new PathValue() { Value = "some path" },
Object = new ObjectValue() { Value = "some object" }
};
XmlAttributeOverrides overrides = new XmlAttributeOverrides();
overrides.Add(typeof(PathValue), "Value", new XmlAttributes() { XmlAttribute = new XmlAttributeAttribute("path") });
overrides.Add(typeof(ObjectValue), "Value", new XmlAttributes() { XmlAttribute = new XmlAttributeAttribute("object") });
XmlSerializer serializer = new XmlSerializer(typeof(Document), overrides);
serializer.Serialize(Console.Out, doc);
Console.WriteLine();
Console.ReadLine();
}
}
Run Code Online (Sandbox Code Playgroud)
......没有做到这一点.