Method overloading based on generic constraints?

后端 未结 4 1418
甜味超标
甜味超标 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 11:59

    This is not possible.

    Generic constraints are not considered to be part of the method signature for purposes of overloading.

    If you want to allow both value types and reference types, why constrain at all?

    0 讨论(0)
  • 2021-01-17 12:00

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

    No. It's not part of the method signature in terms of overloading, just like the return type isn't.

    There are horrible ways of "pseudo-overloading" in some cases, but I wouldn't recommend going down that path.

    For more information, you might want to read:

    • My blog post on the topic
    • Eric Lippert's blog post on the topic
    0 讨论(0)
  • 2021-01-17 12:01
    struct _Val_Trait<T> where T:struct { }
    struct _Ref_Trait<T> where T:class { }
    
    static void Foo<T>(T bar, _Ref_Trait<T> _ = default(_Ref_Trait<T>)) where T:class
    {
        Console.WriteLine("ref");
    }
    
    static void Foo<T>(T bar, _Val_Trait<T> _ = default(_Val_Trait<T>)) where T:struct
    {
        Console.WriteLine("val");
    }
    
    static void Main() 
    {
        Foo(1);            // -->"val"
        Foo(DateTime.Now); // -->"val"
        Foo("");           // -->"ref"
    
        //but:
        //Foo(null); - error: type cannot be inferred
    }
    
    0 讨论(0)
  • 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 t) where T : Reptile { }
    static void Foo(Animal animal) { }
    static void Main() 
    { 
        Foo(new Giraffe()); 
    }
    
    0 讨论(0)
提交回复
热议问题