Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I apply an attribute to an inherited member?

Suppose I have the following (trivially simple) base class:

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

I now want to do the following:

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

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

But without actually redefining the property. I want to apply attributes to members of the base class. Is this possible?

The real problem is that in my serialization mechanism from/to XML (which works brilliantly btw), I find a lot of similar elements where only the names of the attributes differ (they're not consistent, and I don't control the format). Right now I need to create a different class for every such element, whereas they're like 100% the same (apart from the attributes).

I don't think it's possible, but you might never know.

UPDATE:

I tried Marc's approach, but to no avail:

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();
    }
}

...doesn't do the trick.

like image 743
Dave Van den Eynde Avatar asked Jun 24 '09 11:06

Dave Van den Eynde


1 Answers

I'm going to answer this question myself, so that I can accept this answer. I don't like the answer, but I suppose it's the only valid answer.

The answer is: No, you can't do it.

like image 158
Dave Van den Eynde Avatar answered Sep 21 '22 06:09

Dave Van den Eynde