C# 利用反射模拟多态效果


public class A
    {

    }
    public class B : A
    {

    }
    public class C : A
    {

    }

    public static class Extension
    {
        public static void Test(B b)
        {
            Console.WriteLine("this is B");
        }
        public static void Test(A a)
        {
            Console.WriteLine("this is A");
        }
        public static void Test(C c)
        {
            Console.WriteLine("this is C");
        }
    }

internal class Program
    {
        static void ReflectInvoke(List<A> objs)
        {
            MethodInfo[] mis = (from method in typeof(Extension).GetMethods()
                                where method.Name == "Test"
                                select method).ToArray();
            foreach (var a in objs)
            {
                foreach (var m in mis)
                {
                    if (m.GetParameters().First().ParameterType.Name == a.GetType().Name)
                    {
                        m.Invoke(null, new object[] { a });
                        break;
                    }

                }
            }
        }
}

output:


this is A
this is B
this is C

posted @ 2022-10-25 10:22  JohnYang819  阅读(25)  评论(0编辑  收藏  举报