3 回答

TA貢獻1776條經驗 獲得超12個贊
您可以實現明確一個接口和另一個implecitely。
public interface ITest {
void Test();
}
public interface ITest2 {
void Test();
}
public class Dual : ITest, ITest2
{
public void Test() {
Console.WriteLine("ITest.Test");
}
void ITest2.Test() {
Console.WriteLine("ITest2.Test");
}
}
ITest.Test將是默認實現。
Dual dual = new Dual();
dual.Test();
((ITest2)dual).Test();
輸出:
Console.WriteLine("ITest.Test");
Console.WriteLine("ITest2.Test");

TA貢獻1829條經驗 獲得超6個贊
通過顯式實現接口,如下所示:
public interface ITest {
void Test();
}
public interface ITest2 {
void Test();
}
public class Dual : ITest, ITest2
{
void ITest.Test() {
Console.WriteLine("ITest.Test");
}
void ITest2.Test() {
Console.WriteLine("ITest2.Test");
}
}
使用顯式接口實現時,這些函數在類上不是公共的。因此,為了訪問這些功能,必須首先將對象轉換為接口類型,或將其分配給聲明為接口類型的變量。
var dual = new Dual();
// Call the ITest.Test() function by first assigning to an explicitly typed variable
ITest test = dual;
test.Test();
// Call the ITest2.Test() function by using a type cast.
((ITest2)dual).Test();
- 3 回答
- 0 關注
- 777 瀏覽
添加回答
舉報