C# generic method resolution fails with an ambiguous call error

前端 未结 2 1587
灰色年华
灰色年华 2021-02-13 22:09

Suppose I have defined two unrelated types and two extension methods with the same signature but different type filters:

public class Foo {}
public class Bar {}
         


        
2条回答
  •  忘了有多久
    2021-02-13 22:18

    Actually, the general goal (from your description and my practice and view) is more concise representation for sets of “similar” extension for classes. The “similarity” partially may be that names of these classes are quite long multipart camel-case identifiers which even do not always differ in the first part.

    So, using generics is good only in case of class inheritance. For non-inheritable classes solution is using short class aliases.

        public class Foo0987654321 { } 
        public class SucFoo0987654321 : Foo0987654321 { } 
        public class Bar1234567890 { }
    
        namespace NET_Site
        {
            using B = Bar1234567890;
    
            public static class BarExtensions
            {
                public static B Frob(this B bar)
                {
                    // ...
                    return bar;
                }
            }
        }
    
        namespace NET_Site
        {
            using TFoo = Foo0987654321;
    
            public static class FooExtensions
            {
                public static TF Frob(this TF foo)
                    where TF : TFoo
                {
                    // ...
                    return foo;
                }
    
                public static TF Brob(this TF foo)
                    where TF : TFoo
                {
                    // ...
                    return foo;
                }
            }
        }
    
            new SucFoo0987654321()
              .Frob()
              .Brob();
    

提交回复
热议问题