문제

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;
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top