當在多個類中繼承相同的接口時,它是否沒有更新所有具有接口實現的類的問題?例如,如果我有一個由4個類實現的接口,並且將來可能會更多,並且如果我向僅由4個類中的一個類實現的接口添加任何方法,那麼,去這個接口是不是一件乏味的任務並用一個未實現的異常或其他東西來實現其餘的類。我知道你可能會質疑爲什麼我不能將該方法添加到類本身,原因是我在這裏使用了一個工廠,並且我用這些類的對象之一返回了接口的引用。關於我如何能夠採取這種方法的任何想法?對這種情況有沒有其他方法?問題繼承多個類中的相同接口
添加示例代碼對於上述方案
public interface ITest
{
string TestMethod1(string st, int ab);
int TestMethod2(string st);
void TestMethod4(int ab);
float ITest.TestMethod3(string st);
}
public class Class1 : ITest
{
public string TestMethod1(string st, int ab)
{
return string.Empty;
}
public void TestMethod4(int ab)
{
throw new NotImplementedException();
}
public int TestMethod2(string st)
{
throw new NotImplementedException();
}
public float TestMethod3(string st)
{
throw new NotImplementedException();
}
}
public class Class2 : ITest
{
float ITest.TestMethod3(string st)
{
return float.Parse("12.4");
}
void ITest.TestMethod4(int ab)
{
throw new NotImplementedException();
}
public string TestMethod1(string st, int ab)
{
throw new NotImplementedException();
}
public int TestMethod2(string st)
{
throw new NotImplementedException();
}
}
public class Main
{
ITest test = null;
public ITest CreateFactory(TestType testType)
{
switch(testType)
{
case TestType.Class1:
test = new Class1();
break;
case TestType.Class2:
test = new Class2();
break;
}
return test;
}
}
enum TestType
{
Class1,
Class2
}
這聽起來像你需要另一個界面,而不是修改第一個界面。添加一個會引發異常但除了一個實現的成員的想法聽起來是錯誤的。 –
這樣的意思,我爲每個類添加一個接口呢?因爲未來其他班級也可能會發生變化。 – Blossom
接口的要點正是所有實現它的類共享相同的成員。因此,如果你想添加一些成員到界面,你必須爲所有類都這樣做。但正如Charles已經提到的,你也可以定義一個接口 - 例如'IExtendedInterface' - 只有新類實現並且來自已經存在的接口並添加一些新成員。 – HimBromBeere