Note that there are some explanatory texts on larger screens.

plurals
  1. POC# Generics on interface
    primarykey
    data
    text
    <p>I'm creating a generic interface to work as command pattern:</p> <pre><code>public interface IGenericComponent&lt;T&gt; where T : IVisitableObject { void Update(T msg); } </code></pre> <p>Then, I'll have another class that I'll hold a bunch of implementations of this interface (each one with its own type). There I would have a dictionary to put the list of commands to execute like this:</p> <pre><code>private Dictionary&lt;MessageType, List&lt;IGenericComponent&gt;&gt; _components; </code></pre> <p>This generates a compilation error because I don't put the type for the IGenericComponent. I have a thread that calls the Update method and a method to subscribe (inserta an component to the dictionary):</p> <pre><code>public void Subscribe&lt;T&gt;(MessageType messageType, IGenericComponent&lt;T&gt; component) where T : IVisitableObject, new() { lock (_monitorDictionary) { List&lt;IGenericComponent&gt; subscribedList; if (_components.TryGetValue(messageType, out subscribedList)) { subscribedList.Add(component); IVisitableObject firstUpdate; if(_messageBuffer.TryGetValue(messageType, out firstUpdate)) component.Update((T)firstUpdate); } else { subscribedList = new List&lt;IGenericComponent&gt;(); subscribedList.Add(component); _components[messageType] = subscribedList; } } } private void ProcessQueue() { while (true) { IVisitableObject msg; lock (_monitorQueue) { msg = _queue.Dequeue(); } List&lt;IGenericComponent&gt; components; lock(_monitorDictionary) { components = _components[msg.MsgType]; } if(components!= null) { foreach (IGenericComponent genericComponent in components) genericComponent.Update(msg); } } } </code></pre> <p>This code does not compile... I came from Java programming, and in Java I can ommit the parametrized type when I instantiate the type. So... I would like to know if is it possible to do that in C# so it would assume that its the generic type (IVisitableObject). Or if you know a better way to solve this problem... The way I've solved this is not the way I would like to use. I've removed generics from the interface and used the generic type IVisitableObject as the parameter of Update method. Thanks in advance.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload