First of all, I am coming from Java background so please forgive me for my mistakes:
This is my class
class ParameterHandler<T>
{
public static Dictionary<string, Converter<T>> parameters =
new Dictionary<string, Converter<T>>();
public static void addParameter(string parameterName, Converter<T> converter){
parameters.Add(parameterName, converter);
}
static T getValue(string parameterName, string stringValue){
return parameters[parameterName].getValue(stringValue);
}
}
and this is my Converter
interface
interface Converter <T>
{
T getValue(string stringValue);
}
I wonder if I can use the parameterhandler without having to declare T
as a generic type for it
I just need to do something like
ParameterHandler.addParameter("some", Some Implementation for Converter)
and to put you in the whole picture, this is one of my implementation for the Converter
class IntConverter : Converter<int>
{
int getValue(string stringValue)
{
return int.Parse(stringValue);
}
}
You must define an interface that is base for all converters:
interface Converter
{
}
interface Converter<T> : Converter
{
T getValue(string stringValue);
}
Then:
class ParameterHandler
{
public static Dictionary<string, Converter> parameters =
new Dictionary<string, Converter>();
public static void addParameter<T>(string parameterName, Converter<T> converter){
parameters.Add(parameterName, converter);
}
static T getValue<T>(string parameterName, string stringValue){
if(!parameters[parameterName] is Convereter<T>)
throw new Exception("Invalid Type");
return ((Convereter<T>)parameters[parameterName]).getValue(stringValue);
}
}
Note that, in your initial model, you have a different dictionary for each type T
, Converter<int>.parameters
and Converter<double>.parameters
are not the same.