How to pass a Generic class as a parameter to a constructor of a non-generic class

Suppose the following code (read my question in the code comments in the final class):

//This is my Generic Class
public class ClientRequestInfo<K, V>
{
    public string Id { get; set; }
    private Dictionary<K, V> parameters;

    public ClientRequestInfo()
    {
        parameters = new Dictionary<K, V>();
    }

    public void Add(K key, V value)
    {
        parameters.Add(key, value);
    }
 }

public class ProcessParameters()
{
    private void CreateRequestAlpha()
    {
        ClientRequestInfo<int, string> info = new ClientRequestInfo<int, string>();
        info.Add(1, "Hello");
        SynchRequest s = new SynchRequest(info);
        s.Execute();
    }
    private void CreateRequestBeta()
    {
        ClientRequestInfo<int, bool> info = new ClientRequestInfo<int, bool>();
        info.Add(1, true);
        SynchRequest s = new SynchRequest(info);
        s.Execute();
    }
}

public class SynchRequest
{
    //What type should I put here?
    //I could declare the class as SynchRequest<K, V> but I don't want
    //To make this class generic.
    private ClientRequestInfo<????,?????> info;
    private SynchRequest(ClientRequestInfo<?????,?????> requestInfo)
    {
        //Is this possible?
        this.info = requestInfo;
    }

    public void Execute()
    {}
}
+5
source share
4 answers

If you do not want to use SynchRequestInfogeneric, can you create a base class without a common for ClientRequestInfo? -

public abstract class ClientRequestInfo
{
    public abstract void NonGenericMethod();
}

public class ClientRequestInfo<K, V> : ClientRequestInfo
{
    public override void NonGenericMethod()
    {
        // generic-specific implementation
    }
}

Then:

public class SynchRequest
{
    private ClientRequestInfo info;

    private SynchRequest(ClientRequestInfo requestInfo)
    {
        this.info = requestInfo;
    }

    public void Execute()
    {
        // ADDED: for example
        info.NonGenericMethod();
    }
}
+7
source

The class must be shared if you want to use shared member variables.

private ClientRequestInfo<????,?????> info;

It is a common element.

You can use a non-generic base class or interface:

class ClientRequestInfo<K,Y> : IClientRequestInfo

ClientRequestInfo - , / , .

+2

, SynchRequestInfo.

  • Create a non-generic base class using both of them.
  • Provide an interface to use, such as ISynchInfo, and offer your common class to the interface.

In this case, I would prefer an interface approach, since in the future you will want to synchronize other types (separately from client requests).

+1
source

Make ClientRequestInfo (K, V) implement the ClientRequestInfo interface with the functions of the SynchRequest interface.

+1
source

All Articles