简体   繁体   中英

Interfacing with an Abstract Class of Different Derived Class

I have four classes and an interface, something like this:

public interface ISource
{
     DesiredFunc();
}

public class Source
{

}

public class SourceA : Source
{

}

public class SourceAChild : SourceA, ISource
{
     DesiredFunc()
     {
     }
}

public abstract class SourceB : Source, ISource
{
     DesiredFunc()
     {
     }
}

Source and SourceA come from a library so there's no way I can change their implementation. There is a SourceAChild object which calls DesiredFunc() but it needs to use the implementation of DesiredFunc() in SourceB .

What I have done so far is create a wrapper class of SourceB . I create an instance of that class inside of SourceAChild and then call the base method. Something like

public class SourceBChild : SourceB, ISource
{
    DesiredFunc()
     {
          base.DesiredFunc();
     }
}

public class SourceAChild : SourceA, ISource
{
    SourceBChild srcB = new SourceBChild();

     DesiredFunc()
     {
         srcB.DesiredFunc();
     }
}

This seems pretty ugly to me. Is there a better way to get to SourceB's implementation of DesiredFunc() ? One of the biggest problems I can see with the workaround I currently have is data integrity between SourceAChild and SourceBChild because the former class updates its properties frequently.

Thanks in advance for any help.

To call a non-static method of an abstract class, you always need a class instance, and so you will have to subclass it.

If DesiredFunc of SourceB is public , your wrapper class can be simplified to:

public class SourceBChild : SourceB
{
}

The DesiredFunc method will then automatically be exposed. However if it's protected , you'll need to wrap it as you already did.

The last line of your comments doesn't make much sense to me - you mention data integrity and properties, but since DesiredFunc of SourceB runs on an instance of SourceBChild , it can't use the fields or properties of your SourceA instance.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM