Generic Extension Method Ambiguity

后端 未结 6 1573
说谎
说谎 2020-12-09 11:34

I have two interfaces defined:

// IVector.cs
public interface IVector
{
    int Size { get; }

    float this[int index] { get; set; }
}

// IMatrix.cs
publi         


        
6条回答
  •  孤城傲影
    2020-12-09 12:12

    I just found a curious way that works in .NET 4.5 using a trick with Default Parameters.

    /// Simple base class. Can also be an interface, for example.
    public abstract class MyBase1
    {
    }
    
    /// Simple base class. Can also be an interface, for example.
    public abstract class MyBase2
    {
    }
    
    /// Concrete class 1.
    public class MyClass1 :
        MyBase1
    {
    }
    
    /// Concrete class 2.
    public class MyClass2 :
        MyBase2
    {
    }
    
    /// Special magic class that can be used to differentiate generic extension methods.
    public class Magic
        where TInherited : TBase
    {
        private Magic()
        {
        }
    }
    
    // Extensions
    public static class Extensions
    {
        // Rainbows and pink unicorns happens here.
        public static T Test(this T t, Magic x = null)
            where T : MyBase1
        {
            Console.Write("1:" + t.ToString() + " ");
            return t;
        }
    
        // More magic, other pink unicorns and rainbows.
        public static T Test(this T t, Magic x = null)
            where T : MyBase2
        {
            Console.Write("2:" + t.ToString() + " ");
            return t;
        }
    }
    
    class Program
    {
        static void Main(string[] args)
        {
    
            MyClass1 t1 = new MyClass1();
            MyClass2 t2 = new MyClass2();
    
            MyClass1 t1result = t1.Test();
            Console.WriteLine(t1result.ToString());
    
            MyClass2 t2result = t2.Test();
            Console.WriteLine(t2result.ToString());
        }
    }
    

    I am curious to see if this works on MONO compiler (Mcs) Someone wanna try? :)

提交回复
热议问题