开发者

Change the value of an attribute in a derived class?

I have a property in a base class tagged with attributes, and I would like to change some of the attributes in each of my derived classes. What is the best way to do this?

From what I can tell, I have to define the property as abstract in my开发者_如何学JAVA base class and override the property in each of my base class, and redefine all of the attributes. This seems really redundant, and I'm not crazy about it because I would have to repeat the common attributes in each derived class.

This is a simplified example of what I'm trying to do. I want to change MyAttribute in the derived classes but keep all of the other attributes on the property the same and defined in a single place (i.e. I don't want to have to redefine XmlElement more than once). Is this even possible? Or is there a better way to do this? Or am I completely misusing attributes here?

using System;  
using System.Xml;  
using System.Xml.Serialization;

[AttributeUsage(AttributeTargets.Property, AllowMultiple = false)]
public class MyAttribute : System.Attribute  
{  
    public MyAttribute() {}

    public string A { get; set; }

    public string B { get; set; }
}

public abstract class BaseClass  
{  
    public BaseClass() {}

    [XmlElement("some_property")]
    [MyAttribute(A = "Value1", B = "Value2")]
    public string SomeProperty { get; set; }
}

public class FirstDerivedClass : BaseClass  
{  
    //I want to change value B to something else  
    //in the MyAttribute attribute on property SomeProperty  
}

public class SecondDerivedClass : BaseClass  
{  
    //I want to change value B to yet another value  
    //in the MyAttribute attribute on property SomeProperty  
}


You can use the GetCustomAttributes method to return either all of the attributes on all levels of inheritance, or just the implemented class. Unfortunately this wouldn't allow you to override an 'AllowMultiple = false' attribute. You could probably create a method that calls GetCustomAttribute twice, once with inherited values and once without. Then you could give the non-inherited values preference over the inherited values. I can post a sample later if needed.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜