Method overloading based on generic constraints?

后端 未结 4 1420
甜味超标
甜味超标 2021-01-17 11:24

Can I somehow have overloaded methods which differ only by generic type constraints?

This does not compile:

    void Foo(T bar) wh         


        
4条回答
  •  北荒
    北荒 (楼主)
    2021-01-17 12:05

    An update. In C# 7.3 generic constraints are now part of overload decision.

    So, this code will compile:

    class Animal { } 
    class Mammal : Animal { } 
    class Giraffe : Mammal { }
    class Reptile : Animal { } 
    
    static void Foo(T t) where T : Reptile { }
    static void Foo(Animal animal) { }
    static void Main() 
    { 
        Foo(new Giraffe()); 
    }
    

提交回复
热议问题