第四節、訪問接口
對接口成員的訪問
對接口方法的調用和采用索引指示器訪問的規則與類中的情況也是相同的。如果底層成員的命名與繼承而來的高層成員一致,那么底層成員將覆蓋同名的高層成員。但由于接口支持多繼承,在多繼承中,如果兩個父接口含有同名的成員,這就產生了二義性(這也正是c#中取消了類的多繼承機制的原因之一),這時需要進行顯式的定義:
using system ;
interface isequence {
int count { get; set; }
}
interface iring {
void count(int i) ;
}
interface iringsequence: isequence, iring { }
class ctest {
void test(iringsequence rs) {
//rs.count(1) ; 錯誤, count 有二義性
//rs.count = 1; 錯誤, count 有二義性
((isequence)rs).count = 1; // 正確
((iring)rs).count(1) ; // 正確調用iring.count
}
}
上面的例子中,前兩條語句rs .count(1)和rs .count = 1會產生二義性,從而導致編譯時錯誤,因此必須顯式地給rs 指派父接口類型,這種指派在運行時不會帶來額外的開銷。
再看下面的例子:
using system ;
interface iinteger {
void add(int i) ;
}
interface idouble {
void add(double d) ;
}
interface inumber: iinteger, idouble {}
class cmytest {
void test(inumber num) {
// num.add(1) ; 錯誤
num.add(1.0) ; // 正確
((iinteger)n).add(1) ; // 正確
((idouble)n).add(1) ; // 正確
}
}
調用num.add(1) 會導致二義性,因為候選的重載方法的參數類型均適用。但是,調用num.add(1.0) 是允許的,因為1.0 是浮點數參數類型與方法iinteger.add()的參數類型不一致,這時只有idouble.add 才是適用的。不過只要加入了顯式的指派,就決不會產生二義性。
接口的多重繼承的問題也會帶來成員訪問上的問題。例如:
interface ibase {
void fway(int i) ;
}
interface ileft: ibase {
new void fway (int i) ;
}
interface iright: ibase
{ void g( ) ; }
interface iderived: ileft, iright { }
class ctest {
void test(iderived d) {
d. fway (1) ; // 調用ileft. fway
((ibase)d). fway (1) ; // 調用ibase. fway
((ileft)d). fway (1) ; // 調用ileft. fway
((iright)d). fway (1) ; // 調用ibase. fway
}
}
共3頁: 上一頁 1 [2] [3] 下一頁
新聞熱點
疑難解答