Polymorphism Through Extension Methods?

后端 未结 5 1059
有刺的猬
有刺的猬 2021-02-20 05:21

I have a class library which contain some base classes and others that are derived from them. In this class library, I\'m taking advantage of polymorphism to do what I want it t

5条回答
  •  醉梦人生
    2021-02-20 05:52

    Below is the minimal example showing how to mimic polymorphism with extension methods.

    void Main()
    {
        var elements = new Base[]{
            new Base(){  Name = "Base instance"},
            new D1(){    Name = "D1 instance"},
            new D2(){    Name = "D2 instance"},
            new D3(){    Name = "D3 instance"}
    
        };
    
        foreach(Base x in elements){
            x.Process();
        }
    }
    
    public class Base{
        public string Name;
    }
    public class D1 : Base {}
    public class D2 : Base {}
    public class D3 : Base {}
    
    
    public static class Exts{
    
        public static void Process(this Base obj){
            if(obj.GetType() == typeof(Base)) Process(obj); //prevent infinite recursion for Base instances
            else Process((dynamic) obj);
        }
    
        private static void Process(this T obj) where T: Base
        {
            Console.WriteLine("Base/Default: {0}", obj.Name);
        }
    
        public static void Process(this D1 obj){
            Console.WriteLine("D1: {0}", obj.Name);
        }
    
        public static void Process(this D2 obj){
            Console.WriteLine("D2: {0}", obj.Name);
        }
    }
    

    Outputs:

        Base/Default: Base instance
        D1: D1 instance
        D2: D2 instance
        Base/Default: D3 instance
    

提交回复
热议问题