Overload resolution, extension methods, and versatility in C #

I have the following script in my C # source:

class A{}

class Dispatch<T>{}

static class DispatchExt
{
    public static void D<T>(this Dispatch<T> d, int a)
    {
         Console.WriteLine("Generic D chosen with a = " + a.ToString());
    }

    public static void D(this Dispatch<A> d, int a)
    {
         Console.WriteLine("D<A> chosen with a = " + a.ToString());
    }
}

class Program
{
     static void D<T>(Dispatch<T> d, int a)
     {
          d.D(a);
     }

     static void Main(string[] args)
     {
         int a = 5;
         var dispatch = new Dispatch<A>();
         dispatch.D(a);
         D(dispatch, a);
     }
}

When I run this code, the output is:

" D<A>selected with a = 5"

"General D, selected with a = 5"

This result surprised me because I expected it to be " D<A>selected with a = 5" in both situations.

I would like to know what are the general rules for resolving overload in this scenario or something that causes this conclusion. In addition, I am wondering if there is a way to achieve the first exit in both situations.

+4
source share
2 answers

- , , , .

, :

dispatch.D(a);

dispatch Dispatch<A>, . , DispatchExt.D(dispatch, a) ( ).

:

d.D(a);

d Dispatch<T>. , DispatchExt.D<T>(d, a).

, .


. : :

A a = new A();
B b = new B();
A ba = b;

Test(a); // "a"
Test(b); // "b"
Test(ba); // "a"

:

public void Test(A a) { Console.WriteLine("a"); }
public void Test(B a) { Console.WriteLine("b"); }
public class A {}
public class B : A {}
+3

, - , .   .

using System; 

namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {
            var magic = new Magic();
            var sum = magic.MagicAdd(2).MagicAdd(20).MagicAdd(50).MagicAdd(20).Result;
            Console.WriteLine(sum);
            Console.ReadKey();
        }

    }

    public class Magic
    {
        public int Result { get; set; }

        //method chaining
        public Magic MagicAdd(int num)
        {
            this.Sum(num);
            return this;
        }

        public int Sum(int x)
        {
            this.Result = this.Result + x;
            return this.Result;

        }
    }
}
0

Source: https://habr.com/ru/post/1617125/


All Articles