Creating generic types with enumeration values

I would 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 is possible to do this with C #.

So what I would like to do:

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

public enum Metals
{
  Silver, Gold
}

and I would like to list an enumeration like:

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

I think I could create classes called Gold, Silver to achieve this, but I really like to have enum to restrict the types of my general class.

The reason I want something like this in the real world is to create an event aggregator (publish-subscribe model), and I want my subscribers to subscribe to messages of a certain type T. Therefore, I thought it would be nice, if I could subscribe to subscribers using transfers.

EDIT: , Metals.Gold - . , enums\classes . .

+4
2

enum . , , :

public abstract class Metal
{
    protected Metals MetalType { get; private set; }

    protected Metal(Metals metal)
    {
        MetalType = metal;
    }
}

public class Gold : Metal
{
    public Gold() : base(Metals.Gold)
    {
    }
}

, PubSub , . , :

public class EventHub
{
    // only one receiver per message type is allowed to simplify an example
    private static readonly ConcurrentDictionary<MessageTypes, IReceiver> receivers = 
        new ConcurrentDictionary<MessageTypes, IReceiver>();

    public bool TrySubscribe(MessageTypes messageType, IReceiver receiver)
    {
        return receivers.TryAdd(messageType, receiver);
    }

    public void Publish(IMessage message)
    {
        IReceiver receiver;

        if (receivers.TryGetValue(message.MessageType, out receiver))
        {
            receiver.Receive(message);
        }
    }
}

public interface IMessage
{
    MessageTypes MessageType { get; }
    string Text { get; set; }
}

public interface IReceiver
{
    void Receive(IMessage message);
}
+6

, T , .

, , - :

public class MyClass
{
    private readonly Metals _metal;

    public MyClass(Metals metal)
    {
        _metal = metal;
    }

    public void Do()
    {
        //using _metal here
    }
}

var myGoldClass = new MyClass(Metals.Gold);
0

All Articles