我有四个类和一个接口,如下所示:
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
和SourceA
来自库,所以我无法更改它们的实现。 有一个SourceAChild
对象调用DesiredFunc()
但它需要使用SourceB
中的DesiredFunc()
实现。
到目前为止,我所做的是创建一个SourceB
的包装类。 我在 SourceAChild
中创建该类的实例,然后调用基方法。类似的东西
public class SourceBChild : SourceB, ISource
{
DesiredFunc()
{
base.DesiredFunc();
}
}
public class SourceAChild : SourceA, ISource
{
SourceBChild srcB = new SourceBChild();
DesiredFunc()
{
srcB.DesiredFunc();
}
}
这对我来说似乎很丑陋。 有没有更好的方法来实现SourceB's
DesiredFunc()
? 我目前遇到的解决方法中可以看到的最大问题之一是SourceAChild
和SourceBChild
之间的数据完整性,因为前一个类会经常更新其属性。
提前感谢任何帮助。
要调用抽象类的非静态方法,您始终需要一个类实例,因此您必须对其进行子类化。
如果DesiredFunc
SourceB
public
,您的包装类可以简化为:
public class SourceBChild : SourceB
{
}
然后,将自动公开DesiredFunc
方法。但是,如果它是 protected
,您需要像以前一样包装它。
您评论的最后一行对我来说没有多大意义 - 您提到了数据完整性和属性,但由于DesiredFunc
SourceB
在 SourceBChild
的实例上运行,因此它无法使用SourceA
实例的字段或属性。