![](/img/trans.png)
[英]Can a C# class call an interface's default interface method from its own implementation?
[英]Can we call method in implementation class not defined in its interface using interface variable?
是否可以在接口的實現類中調用一個方法,該接口未使用接口變量在接口中定義,如下所示:
interface ILookup {
public void someInterfaceMethod1();
public void someInterfaceMethod2();
}
......和實施類:
public class extendedLookUpImplementor: ILookup
{
//constructor
LookUpImplementor(){
}
public void someInterfaceMethod1(){
// Implementation Code here.
}
public void someInterfaceMethod2(){
// Implementation Code here.
}
public void ExtendedMethod(){
// Implementation Code here.
}
}
在客戶端代碼中:
ILookup lookupVar = new LookUpImplementor();
lookupVar -> someInterfaceMethod1(); // i know it will work.
lookupVar -> someInterfaceMethod2(); // i know it will work.
我的問題是,我可以使用lookupVar調用ExtendedMethod,如下所示:
lookupVar -> ExtendedMethod(); // Note again that ExtendedMethod() is not defined in Ilookup interface/contract.
只能通過將lookupVar強制轉換為extendedLookUpImplementor,或者通過反射我認為。
首先,正如Ian1971所說的那樣,是的,你可以把它投射到特定類型,比方說
ILookup lookupVar = new LookUpImplementor();
((extendedLookUpImplementor)lookupVar).ExtendedMethod(); //this should work
或者使用動態/反射。
話雖如此,我真的不認為這是一個很好的方法,因為它會違反合同/接口的目標之一。
例如,如果我們有ILookup變量“lookupVar”
dynamic lookup = lookupVar;
lookup.ExtendedMethod(); //this would work
在任何時候,使用對象lookupVar的代碼都不能保證會有一個方法ExtendedMethod並且可以在運行時拋出異常。
我真正的問題是,為什么要添加一個無法在合同中添加的方法,這里的目標是什么。 如果該方法正在擴展該類,請嘗試使用C#擴展方法,因為它們可能適合您的方案。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.