namespace NUnitTestAbstract
{
public abstract class BaseTestClass1
{
public abstract void BaseTestClass1Method();
}
public abstract class BaseTestClass2 : BaseTestClass1
{
// not overriding BaseTestClass1Method, child classes should do
public void SomeTestMethodA() { }
public void SomeTestMethodB() { }
}
public abstract class BaseTestClass3 : BaseTestClass1
{
// not overriding BaseTestClass1Method, child classes should do
public void SomeTestMethodX() { }
public void SomeTestMethodY() { }
}
public class TestClass2A : BaseTestClass2
{
public override void BaseTestClass1Method()
{
// do stuff
}
}
public class TestClass2B : BaseTestClass2
{
public override void BaseTestClass1Method()
{
// do same stuff as TestClassA
}
}
public class TestClass3A : BaseTestClass3
{
public override void BaseTestClass1Method()
{
// do stuff
}
}
public class TestClass3B : BaseTestClass3
{
public override void BaseTestClass1Method()
{
// do same stuff as TestClass3A
}
}
}
在這一刻我有上述建設。擴展另一個基類的基類。基類由兩個子類擴展。 BaseTestClass1Method
的實現對於兩個子類是相同的。如果可以從兩個父母延伸,我會創建一個延伸BaseTestClass1
的類,實現BaseTestClass1Method
。然後這兩個子類將擴展BaseTestClass2
和新類,以便我只需要實現BaseTestClass1Method
一次 當我添加另一個BaseTestClass3(與BaseTestClass2相同級別)從BaseTestClass1擴展並從中創建子類時,我有更多的重複代碼實施BasetestClass1Method。 如何用正確的模式解決這個問題?c#繼承多個父母
以下是一個實現的例子:
namespace NUnitTestAbstract
{
public interface IServer { }
public abstract class ServerBase
{
public abstract IServer GetServerInstance();
}
public abstract class SomeTests1Base : ServerBase
{
// not overriding BaseTestClass1Method, child classes should do
public void SomeTestMethodA() { }
public void SomeTestMethodB() { }
}
public abstract class SomeTests2Base : ServerBase
{
// not overriding BaseTestClass1Method, child classes should do
public void SomeTestMethodX() { }
public void SomeTestMethodY() { }
}
public class TestClass2A : SomeTests1Base
{
public override IServer GetServerInstance()
{
IServer serverX = null;
return serverX;
}
}
public class TestClass2B : SomeTests1Base
{
public override IServer GetServerInstance()
{
IServer serverX = null;
return serverX;
}
}
public class TestClass3A : SomeTests2Base
{
public override IServer GetServerInstance()
{
IServer serverY = null;
return serverY;
}
}
public class TestClass3B : SomeTests2Base
{
public override IServer GetServerInstance()
{
IServer serverY = null;
return serverY;
}
}
}
如果BaseTestClass1Method真的是一樣的,那麼爲什麼不只是製作BaseTestClass1具體並在那裏實現該方法呢?您可以對子類中可能有所不同的任何屬性/方法進行保護性覆蓋。或者我錯過了什麼? – kpollock