Polymorphism Through Extension Methods?

后端 未结 5 1056
有刺的猬
有刺的猬 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

    If you can not use the keyword "dynamic" (older version of .NET), you can use reflection to achieve the same thing.

    In place of :

    Base base1 = new Child1();
    Extensions.DoSomething(base1 as dynamic);
    

    you can write :

    Base base1 = new Child1();
    
    MethodInfo method = typeof(Extensions).GetMethod("DoSomething", new System.Type[] { base1.GetType() });
    if (method) {
        method.Invoke(new object[] { base1 });
    }
    

提交回复
热议问题