简体   繁体   中英

Alternative to if/then when using generics

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'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 could probably overload the method instead:

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

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

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() { }

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM