Generic method with type constraints or base class parameter

前端 未结 5 1137
清歌不尽
清歌不尽 2021-02-05 04:07

If I write a method accepting a parameter which derives from a BaseClass (or an interface), as far as I know there are two ways to achieve that:

voi         


        
5条回答
  •  悲&欢浪女
    2021-02-05 04:29

    In this example there isn't a big difference between the two, you can access the same members inside the method and you can call it with the same derived classes. There is a runtime difference as a generic method is compiled for each type it is invoked with.

    Where generics come in useful would be if you would return a value depending on T

    With generics you could do the following

    T MyMethod(T obj) where T : BaseClass { ... }
    MyMethod(derivedInstance).derivedProperty
    

    Without this would be an error:

    BaseClass MyMethod(BaseClass obj) { ... }
    MyMethod(derivedInstance).derivedProperty // error
    

    Note Although you mention constraining to a base class, it is worth mentioning that if you constrain not to a class, but to an interface, extra boxing will occur if the implementation is by a struct in the non generic version, this can have severe performance implications.

提交回复
热议问题