I want to make attribute of some fields conditional, as below:
enum AttrType
{
Type1,
Type2
}
public class Shape
{
[MyAttribute(AttrType.Type1)]
mArea;
}
public class Circle:Shape
{
[Make it AttrType.Type2]
mArea;
[Make it AttrType.Type1]
mRadius;
}
If it is base class A, and mRadius is not defined, I want mArea has AttrType.Type1. If it is in derived class B, and mRadius is defined, I want mArea has AttrType.Type2 and mRadius has AttrType.Type1
How to make it work?
Thanks,
Loading
VulpesPosted Apr 27, 2012, 11:01 AM
Ken ShenPosted Apr 26, 2012, 10:07 PM
I agree that it is easy work that we use abstract properties (e.g.Area) in base class and override it in derived classes. However, there are two reasons I don't use in my case: (1) There are many fields whose attributes are to be changed in the problem I am thinking of. Using override properties or fields will make the code bulky. (2) Sometimes, we want to use the base class (e.g. Shape) if we don't know the exact kind of shape. In this case, we just need to construct and use a Shape instance with mArea value.
What I am trying is to create a static information sheet or class, which is constructed and collects MyAttribute information of multiple classes only ONCE between compiling and running. This sheet also updates MyAttribute information during its construction based on the following custom attribute,
[AttributeUsage(AttributeTargets.Class, AllowMultiple = true)]
public class ResetMyAttribute : Attribute
Also I want to realize that: If AttrType.Type1, then this field is Serializable. If AttrType.Type2, then this field is NonSerializable. This is kind of attribute dependency question. Is is feasible?
Thanks,
VulpesPosted Apr 24, 2012, 10:44 AM
Ken ShenPosted Apr 24, 2012, 2:44 AM
As in my earlier case, Shape.mArea can be readable/writable, however, Circle.mArea is only readable as it can be calculated from Circle.mRadius. So by letting Type1 be 'rw', and Type2 be 'r', we define the attribute to control the accessibility of similar fields. That's the origin of my question.
It is true as you mentioned that we can redefine Circle.mArea, but it will make derived classes not concise and large, for general cases.
So the basic question I was trying to ask is that if there is a way to modify attributes of inherited fields in compile time? A method, constructor in CustomAttribute or whatever.
VulpesPosted Apr 23, 2012, 10:26 AM