mercredi 27 avril 2016

Creating generic types with enum values

I'd like to be able to create new generic types using enum values. I believe this is possible with C++ templates, but I don't know if it's possible to do with C#.

So what I'd like to do is:

public class MyClass <T>
{
  public void Do<T>() {} 
}

public enum Metals
{
  Silver, Gold
}

and I'd like to pass in an enum like:

var myGoldClass = new MyClass<Metals.Gold>();

I guess I could create classes called Gold, Silver to achieve this, but I quite like having an enum to constrain the types of my generic class.

The reason I want something like this in the real world is I'm creating an event aggregator (a publish-subscribe model) and I'd want my subscribers to subscribe to messages of a certain type T. So i thought it would be nice if i could have my subscribers subscribe using enums.

EDIT: To clarify, Metals.Gold is just an example enum. I'd like the client library to create their own enums\classes and use it instead. I'm not defining the enum myself.

Aucun commentaire:

Enregistrer un commentaire