Why use generic constraints in C#

前端 未结 7 1723
日久生厌
日久生厌 2020-11-29 05:48

I\'ve read an excellent article on MSDN regarding Generics in C#.

The question that popped in my head was - why should i be using generic constraints?

For ex

7条回答
  •  星月不相逢
    2020-11-29 06:29

    Consumer of your class gets the benefit of increased type-safety, among others.

    class Widget : IPokable { }
    
    // No generics
    Widget w = (Widget)list[0]; // cast can fail
    
    // With generics
    Widget w = list[0];
    

    Without generics, if list was containing IPokable objects, cast is still necessary.

    Class you're implementing gets the benefit of using specific methods on the generic object.

    class PokableList where T : IPokable {
        public T PokeAndGet() {
            currentObj.Poke();
            return currentObj;
        }
    }
    

提交回复
热议问题