Generic method with type constraints or base class parameter

前端 未结 5 1134
清歌不尽
清歌不尽 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:28

    When T is constrained to a base class, there is not really much difference apart from what has already been stated.

    When T is constrained to an interface, the difference can be huge:

    int FrobNonGeneric(IFrobbable frob) { //... }
    int Frob(T frob) where T: IFrobbable { //... }
    
    struct Frob: IFrobbable { ... }
    
    FrobNonGeneric(new Frob()); //boxing!
    Frob(new Frob()); //no boxing
    

提交回复
热议问题