How do extension methods work under-the-hood?

后端 未结 6 1098
半阙折子戏
半阙折子戏 2021-02-13 12:56

A contractor where I work is using extension methods to implement CRUD on well-known internal classes that we own. I say it is better

6条回答
  •  离开以前
    2021-02-13 13:33

    In answer to the first question:

    Under the hood, extensions act as Delegates, such that void MyExtension(this object obj) could be rewritten as Action MyDelegate. Where they differ, though, is in syntax when called, as Action must wrap around the object, whereas extensions can be called as if it were a member of the object itself, even though under the hood it is not (nor does it have any direct access to private or protected members of the object, for that matter).

    In answer to the second question:

    I usually reserve extensions for either classes I do not own or Interfaces.

    For example, say you have an interface IAnimal

    Public Interface IAnimal
    {
        void Speak();
        void RunToOwnerWhenCalled();
    }
    

    And the following classes

    public class Mammal
    {
        public virtual void AnswerWhatAmI()
        {
            Console.WriteLine("I'm a mammal");
        }
    }
    
    public class Dog:Mammal, IAnimal
    {
        public void Speak()
        {
            Console.WriteLine("arf");
        }
    
        public void RunToOwnerWhenCalled()
        {
            Console.WriteLine("Comming");
        }
    }
    
    public class Cat:Mammal, IAnimal
    {
        public void Speak()
        {
            Console.WriteLine("meow");
        }
    
        public void RunToOwnerWhenCalled()
        {
            Console.WriteLine("I don't know you");
        }
    }
    

    Then you could have an extension like

    Public static void CallAnimal(this IAnimal animal)
    {
        animal.RunToOwnerWhenCalled();
    }
    

    And a method like

    Public static void Main
    {
        Cat cat = new Cat();
        cat.CallAnimal();
    }
    

    and the result would show the cat's response "I don't know you" in Console.

    Consider one more class

    Public class Human:Mammal
    {
        Public Human():base()
        {
            Console.WriteLine("To be more specific, I am a human.");
        }
    }
    

    This class wouldn't have the CallAnimal extension, as it does not impliment the IAnimal interface, even though it is a type of Mammal.

提交回复
热议问题