سؤال

What is the better alternative to use of if/then in the following logic:

    public void DoSomething <T>()
    {
        if (typeof (T) == typeof (A))
        {

        }
        else if (typeof (T) == typeof (B))
        {

        }

    }
هل كانت مفيدة؟

المحلول

You could probably overload the method instead:

public void DoSomething(A item)
{
   ...
}

public void DoSomething(B item)
{
   ...
}

نصائح أخرى

You're right that is a code smell.

Something like:

public void DoSomething <T>() where T : A
{

}

public void DoSomething <T>() where T : B
{

}

If you are doing this though, then it stuill feel a bit smelly. A better solution would to have both A & B inherid a common interface and then have a single method where T : IMyNewInterface.

If that's really not possible then this might not be a problem to solve this way, or the architecture might need revisiting.

CORRECTION

The above code is not valid, as Eric stated in the comment below. Generics do not form part of the signature, so can't be used in a overload.

The only other option is a normal overload:

public void DoSomething(A a)
{

}

public void DoSomething(B b)    {

}

You probably want your objects to be of a similar type or have similar method naming when you're using generics.

With what you've described, this is my preferred pattern:

public void DoSomethingA() { }
public void DoSomethingB() { }
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top