Assume the following code (Please 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()
{}
}
Yes, There are two level where you can apply generic type . You can apply generic type on Method level as well as Class level (both are optional). As above example you applied generic type at method level so, you must apply generic on method return type and method name as well. You need to change a bit of code.
Yes you can do it.
A generic class can extend a non-generic class.
An attribute cannot inherit from a generic class, nor can a generic class inherit from an attribute.
If you don't want to make SynchRequestInfo
generic, can you make a non-generic base class 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();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With