Overload resolution, extension methods and genericity in C#

你说的曾经没有我的故事 提交于 2019-12-05 17:27:50

Extension methods are syntactic sugar that is interpreted at compile-time using information taken from the static type system only.

Taking your first example, you have this:

dispatch.D(a);

dispatch is of type Dispatch<A>, for which an extension method exists. So the compiler translates this into DispatchExt.D(dispatch, a) (the non-generic version).

In your second example, you have this:

d.D(a);

d is of type Dispatch<T>. So this takes the generic extension method DispatchExt.D<T>(d, a).

Since the translation happens at compile-time, the actual run-time type is not taken into account.


This is btw. the same behavior used when determining overloads in other situations: Only the static compile-time type is taken into account:

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

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

Using the following definitions:

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

I think you mean like this -- a chaining method that calls itself. I did a multiple calls of sum of numbers.

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;

        }
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!