C
C#3y ago
Emporware

❔ Generalise Attributes?

Is there a way to generalise Attributes? I'd like to create a library in which I can just pass in what Enum to watch out for. So I'd like to replace the EPartnership/ECategory enum with any enum passed into the attribute. What would be the smartest way to get around this?
[AttributeUsage(AttributeTargets.Method, AllowMultiple = true)]
public class EventPartnershipControllerAttribute : Attribute
{
public EPartnership Event { get; set; }

public EventPartnershipControllerAttribute(EPartnership Event)
{
this.Event = Event;
}
}
public class EventController
{
[EventControllerAttribute(ECategory.PARTNERSHIP)]
public static async void PartnershipController(string[] ids, object e)
{
// Foo...
[AttributeUsage(AttributeTargets.Method, AllowMultiple = true)]
public class EventPartnershipControllerAttribute : Attribute
{
public EPartnership Event { get; set; }

public EventPartnershipControllerAttribute(EPartnership Event)
{
this.Event = Event;
}
}
public class EventController
{
[EventControllerAttribute(ECategory.PARTNERSHIP)]
public static async void PartnershipController(string[] ids, object e)
{
// Foo...
6 Replies
Pobiega
Pobiega3y ago
[AttributeUsage(AttributeTargets.Method, AllowMultiple = true)]
public class EventPartnershipControllerAttribute<T> : Attribute
{
public T Event { get; set; }

public EventPartnershipControllerAttribute(T Event)
{
this.Event = Event;
}
}

public enum MyEnum
{
asd,
twasd
}

public class ASD
{
[EventPartnershipController<MyEnum>(MyEnum.asd)]
public void Method()
{

}
}
[AttributeUsage(AttributeTargets.Method, AllowMultiple = true)]
public class EventPartnershipControllerAttribute<T> : Attribute
{
public T Event { get; set; }

public EventPartnershipControllerAttribute(T Event)
{
this.Event = Event;
}
}

public enum MyEnum
{
asd,
twasd
}

public class ASD
{
[EventPartnershipController<MyEnum>(MyEnum.asd)]
public void Method()
{

}
}
seems to work fine?
Emporware
EmporwareOP3y ago
Ah, right. Generics. I'm dumb lol Thank you Ah, I see. That's why I didn't know about it. Generic Attributes aren't a thing yet in .NET 6.0
Pobiega
Pobiega3y ago
Ah. I tested on 7. Is upgrading an option?
Anton
Anton3y ago
In earlier versions, pass object or Enum. It's not gonna be typesafe, but that's the best you can do The other option would be making a generic one, and subclassing on that. The you can apply the concrete attribute types
Emporware
EmporwareOP3y ago
Yeah, that works for me. That just explained why I didn't know of it. 😄
Accord
Accord3y ago
Was this issue resolved? If so, run /close - otherwise I will mark this as stale and this post will be archived until there is new activity.

Did you find this page helpful?