Polymorphism Through Extension Methods?

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

    As @SLaks has already stated you cannot call the method as an extension method (even with a dynamic type) ... you can however call the static method with a dynamic type

    So, although this will fail

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

    This will work

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

提交回复
热议问题