简体   繁体   中英

What is the difference between a generic method limited by inheritance and a base class parameter?

Suppose I have the following code:

public class BaseClass { }
public class DerivedClass : BaseClass { }

public void GenericMethod<T>(T input) where T : BaseClass
{
 //code
}

public void NormalMethod(BaseClass input)
{
 //code
}

My question is what is the difference between the two methods? Is there any advantages or disadvantages to either method, and why?

What is the difference between the two methods?

Basically none.

Is there any advantages or disadvantages to either method?

At best there is a slight (compile-time) performance improvement when you use the non-generic version, since that doesn't need a specific version of the method to be compiled. Otherwise, there is nothing significant I can think of.

What could be a use case for using generics here:

  • When you would return T ;
  • When T needs to derive from a class and an interface;
  • If your class uses a type argument, you could follow that over specifying the required type again.

It makes little sense to use generics in the code you show.

On the other hand, if you were to return T as opposed to BaseClass from that method, the caller can access T -specific members instead of only members declared on BaseClass (unless they cast the return value).

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