gpt4 book ai didi

c# - 我可以将属性应用于继承的成员吗?

转载 作者:太空狗 更新时间:2023-10-29 18:33:41 28 4
gpt4 key购买 nike

假设我有以下(非常简单的)基类:

public class Simple
{
public string Value { get; set; }
}

我现在想做以下事情:

public class PathValue : Simple
{
[XmlAttribute("path")]
public string Value { get; set; }
}

public class ObjectValue : Simple
{
[XmlAttribute("object")]
public string Value { get; set; }
}

但实际上并没有重新定义属性。我想将属性应用于基类的成员。这可能吗?

真正的问题是,在我的从/到 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();
}
}

...行不通。

最佳答案

我要自己回答这个问题,这样我才能接受这个答案。我不喜欢这个答案,但我想这是唯一有效的答案。

答案是:不,你做不到。

关于c# - 我可以将属性应用于继承的成员吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1037842/

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