Question

I'm creating a custom attribute in C#.

So I have something like this:

[AttributeUsage(AttributeTargets.Property)]
public class Something : Attribute
{
   public Something
   {
       Assembly a = Assembly.GetCallingAssembly();
   }
}

The code above will give me the assembly name of the assembly where the attribute is being called from.

What I would like to know is if there is a way to get the name and type of the property to which the attribute was added. So as an example if I had:

// This should return System.Int32 and MyString
[Something]
public int MyInt {get; set;}

// This should return me System.String, and MyString
[Something]
public string MyString {get; set;}

Is there any way to get those values upon adding the attribute, or will I have to resort to looping trough all the properties in the type and see which ones have an attribute assigned to them?

Thanks in advance.

Était-ce utile?

La solution

There is no other way then iterating over the properties and check the attributes. But you should be able to do this in one Linq statement.

Use GetCustomAttributes on the GetProperties method of the types.

You could optimize the performance, if you mark all classes that use this attributes are marked by an interface, common base class or an class attribute. So you could prefetch the classes instead to iterate over all types.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top