Generic method with type constraints or base class parameter

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

    As was said, it matters only once you get a return value. Consider these cases:

    BaseClass MyMethod(BaseClass)

    DervivedClass temp = new DervivedClass();
    //Error. My Method always returns a BaseClass. No implicit casting available
    temp = MyMethod(temp);
    

    Compare it to this:

    T MyMethod(T) where T : BaseClass

    DervivedClass temp = new DerivedClass();
    temp = MyMethod(temp);
    

    Strong Typification is one of the best friends you have in .NET. Embrace it. Never try to avoid it. The opposite would be cases like we have in PHP and JavaScript: http://www.sandraandwoo.com/2015/12/24/0747-melodys-guide-to-programming-languages/

提交回复
热议问题