dimanche 7 février 2016

Is it possible in c# to get the attributes attached to a property from within the instance of that property, without knowing the containing class?

The title is a bit of a mouthful, but it's easier to see in code:

public struct MyStruct {
    public bool HasAttribute(Attribute attribute) {
        //is there any way to know?
        return ??????;
    }
}

public class MyClass {
    [SomeAttribute]
    MyStruct child;

    public MyClass() {}
}

I already know how to find the attributes on MyClass.child by getting the property info for each of its properties and then calling GetCustomAttributes. What I'd like to do here is to figure out if a particular instance of a struct has attributes attached to it, without knowing what class contains the particular instance.

It would make sense to me if you couldn't do this for reference types because the instance could be referenced from multiple places, but shouldn't the set of attributes always be well-defined for value types?

My use case is making a library where the behavior of certain objects can be modified slightly by attaching custom attributes. If there's a more idiomatic way to approach this then I'm open to suggestions. I'm also willing to go into an unsafe context if that allows for a solution.





Aucun commentaire:

Enregistrer un commentaire