Wednesday, August 17, 2011

接口的显式实现

如果一个类,继承了2个接口,并且这两个接口有相同的方法.
public interface IFile{void Close();}
public interface IWindow(void Close(); }

public class FileWindow:IFile;IWindow
{
void IFile.Close(){...} //这样没有public字样的就是显式实现.他们默认地都是私有的
void IWindow.Close(){...}

public void Close(){
(this as IFile).Close(); //如果想调用其他的接口的方法, 必须先把相关对象转换成相应的接口类型. this是当前class的实例.
((IWindow)this).Close();
}//自己的close方法

}

//调用时
public static void Test(){
IFile file = new FileWindow();
IWindow = new FileWindow();
FileWindow fw = new FileWindow();

file.Close();
window.Close();
fw.Close();
}

No comments: