Click here to Skip to main content
15,881,938 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have a AAA class with a custom attribute XXX, is it possible to get the AAA instance and the Property where the attribute is used in the attribute constructor?

Class where is Attribute used.

public class AAA
{
    int _property;
    [XXX]
    public int Property { get { return _property; } set { _property = value; } }


}


Attribute constructor - is it possible to get access the AAA class instance and the property where the attribute is used?

public class XXX : JsonAttribute
{

    public XXX()
    {
        //???



    }


}


What I have tried:

I tried going through the object this in the constructor in the debugg mod to see if I can find any mention of what I'm looking for.
Posted
Comments
PIEBALDconsult 12-Oct-21 9:27am    
Pretty sure not. In fact, the Attribute could be used on something static and there won't be an instance.

Maybe in the constructor for AAA, it could access its XXX and introduce itself?
KarNullKa 12-Oct-21 9:51am    
Okay. How about reflecting the AAA class to find the attribute XXX in the AAA constructor and then replacing it with another one? Because I would already have access to the instance data in the constructor.
PIEBALDconsult 12-Oct-21 10:07am    
Uhhh... what?
If I follow that, no, that won't work.
You can definitely get an instance of XXX from the AAA's constructor, but you can't _replace_ it -- not in a way which will cause other pieces of code to see the replacement. Attributes don't work that way.
KarNullKa 12-Oct-21 10:25am    
I was wondering if it's possible to make a simple attribute that only has e.g. true/false information. After calling the constructor of the AAA class, go through all the properties using reflection and if it has the XXX attribute set and the value set to true, add another attribute to the properties such as [JsonIgnore]. This results in the [JsonIgnore] attribute, but it depends on what data the AAA class contains and the setting of the XXX attribute.
PIEBALDconsult 12-Oct-21 10:56am    
Yeah, no. Attributes are limited in what you can do with them. You would simply write the class with the Attributes you want. Attributes are set when you write them. Any other class can query the definition to get the set of Attributes, but can't see any instances of the class which may exist already.

Potentially, you could write an Attribute by which your AAA instances could let all other AAA instances know about each other, but non-AAA classes wouldn't know about it.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900