I have a bunch of methods that create same result type ,but their parameter type varies.Assume int
is the result type ,and bool
, int
, float
,etc,etc, and prototype are like this:
int method1(int param1);
int method2(bool param1);
int method3(float param1);
how can I refactor them to looks like this:
int methodGenericVersion1<T>(T arg1);
By the way ,I cannot see the implementation of those non-generic methods.
EDIT
I want to invoke like this:
methodGenericVersion1<int>(param1);
methodGenericVersion1<bool>(param1);
methodGenericVersion1<float>(param1);
It sounds like you want to dispatch to the 'correct' method based on the actual generic type, like so:
public int GenericMethod<T>(T t)
{
if (t is int)
{
return method1(t as int);
}
else if (t is bool)
{
return method2(t as bool);
}
else if (t is float)
{
return method3(t as float);
}
...
throw new ArgumentInvalidException(...);
}
However, if the goal is to provide a "single method" that can be used polymorphically across a limited range of types, then I question why a generic is necessary. You can use method overloading and get exactly the same developer experience, like so:
public int method(int arg)
{
return method1(arg);
}
public int method(bool arg)
{
return method2(arg);
}
public int method(float arg)
{
return method3(arg);
}
You are so close.Just you need to specify generic parameter within the method name like this:
int methodGenericVersion1<T>(T arg1)
Also you might want to add a struct
constraint if you want to pass value types only:
int methodGenericVersion1<T>(T arg1) where T : struct
You can do something like this:
int Test<T>(T v)
{
return -1;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.