Method overloading based on generic constraints?

后端 未结 4 1417
甜味超标
甜味超标 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:01

    struct _Val_Trait where T:struct { }
    struct _Ref_Trait where T:class { }
    
    static void Foo(T bar, _Ref_Trait _ = default(_Ref_Trait)) where T:class
    {
        Console.WriteLine("ref");
    }
    
    static void Foo(T bar, _Val_Trait _ = default(_Val_Trait)) 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
    }
    

提交回复
热议问题