I really like attributes in .NET. So much so that I co-authored a book on them a long time ago. The only thing that's been kind of annoying is that custom attributes don't support generics ... at least I thought they didn't until today. I ran across this article and I found out you can use generics with attributes, but you can only do it at the IL level. Now, there's a number of things I know you can do in IL that aren't available in languages like C# and VB, and even if you try to define stuff in IL you can't consume it in C# (like overloading methods by return type only), but thankfully generic attributes are consumable in "normal" .NET languages! Here's a simple example on how you can do this. Let's say you want to have a generic attribute like this:[AttributeUsage(AttributeTargets.Class)]
public abstract class MyGenericAttribute<T> : Attribute
{
protected MyGenericAttribute(); public abstract void Consume(T target);
}Rather than trying to figure out the IL by hand, I created two classes in C#, one that defines the attibute, and one that defines the generic portion:[AttributeUsage(AttributeTargets.Class)]
public abstract class MyGenericAttribute : Attribute { }public abstract class MyGenericAttributeMock<T>
{
public abstract void Consume(T target);
}
Read more: jasonbock.net
QR:
public abstract class MyGenericAttribute<T> : Attribute
{
protected MyGenericAttribute(); public abstract void Consume(T target);
}Rather than trying to figure out the IL by hand, I created two classes in C#, one that defines the attibute, and one that defines the generic portion:[AttributeUsage(AttributeTargets.Class)]
public abstract class MyGenericAttribute : Attribute { }public abstract class MyGenericAttributeMock<T>
{
public abstract void Consume(T target);
}
Read more: jasonbock.net
QR:
0 comments:
Post a Comment