[英]how to use a class with generics without having to declare the generic type
First of all, I am coming from Java background so please forgive me for my mistakes: 首先,我来自Java背景所以请原谅我的错误:
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 这是我的Converter
界面
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 我想知道我是否可以使用parameterhandler而不必将T
声明为它的泛型类型
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
并且为了全面了解,这是我对Converter
实现之一
class IntConverter : Converter<int>
{
int getValue(string stringValue)
{
return int.Parse(stringValue);
}
}
You can create a non-generic ParameterHandler class with a generic addParameter
method: 您可以使用通用addParameter
方法创建非泛型ParameterHandler类:
public static class ParameterHandler
{
public static void addParameter<T>(string name, Converter<T> c)
{
ParameterHandler<T>.addParameter(name, c);
}
}
then you can use 然后你可以使用
ParameterHandler.addParameter("some", new IntConverter());
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. 请注意,在初始模型中,每个类型T
都有不同的字典, Converter<int>.parameters
和Converter<double>.parameters
不相同。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.