Polymorphism Through Extension Methods?

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

    I was looking for the same thing just now.

    You could add one more method to your extension class like this:

    public static void DoSomething(this Base myObj, Object dependency)
    {       
        if(myObj.IsSubclassOf(Base))
        {
          // A derived class, call appropriate extension method.  
          DoSomething(myObj as dynamic, dependency);
        }
        else
        {
            // The object is Base class so handle it.
        }
    } 
    

    You don't need the if/else check if the base class is abstract (or never used in the wild):

    public static void DoSomething(this Base myObj, Object dependency)
    { 
        DoSomething(myObj as dynamic, dependency);
    }
    

    [Edit] Actually this won't work in your case as you don't implement support for all derived objects (so could still get infinite recursion). I guess you could pass something to check for recursion but the given answer is the simplest. I'll leave this here as it might spark more ideas.

提交回复
热议问题