MemberInfo for Attribute target

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

Hi. In a custom attribute, is there any way for me to discover the
type/member to which the attribute is applied during attribute construction?
For example:

public enum MyEnum
{
[MyCustomAttribute()]
MyField,
...
}

public MyCustomAttribute : Attribute
{
public MyCustomAttribute()
{
// here I would like to discover the type to which
// the attribute is being applied
// e.g. in this example MyEnum.MyField
}
}

Many thanks

kh
 
I don't think you can. Sorry.

What is it that you want it to do? There may be other ways to achieve
your aim...

Marc
 
I have an attribute with AllowMultiple=true but the instance of each
Attribute applied to a member must be unique, using some value on the
attribute as a key. For example

public class MyUniqueAttribute : Attribute
{
public readonly string Key;
public MyUniqueAttribute(string key)
{
Key = key;
}
}

I want to be able to check uniqueness such that the following would work for
MyField1 (because the key values are unique) but would throw for MyField2 in
some way:

public MyEnum
{
[MyUniqueAttribute("One")]
[MyUniqueAttribute("Two")]
MyField1,

[MyUniqueAttribute("One")]
[MyUniqueAttribute("One")]
MyField2
}

I know I can do this by reflecting over all usages of the custom attribute,
but I thought a self-checking attribute (which maintains a registry, by Type,
of all "Key" values applied to the Type) would be a more elegant solution.

Any ideas appreciated

kh
 
Personally I would add some "#if DEBUG" code to check this at runtime
(by reflecting over all types, perhaps walking the reference tree).
You could perhaps add some code to a key static constructor so that it
is hard to avoid. Or a unit test if you use such.
It would be hard (impossible?) to do at compile-time, which is what
you really want...

Marc
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top