是否可以实例化接口

是否可以实例化接口

本文介绍了是否可以实例化接口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有阅读界面无法直接在MSDN中实例化



但是只有在给出一个例子的时候他们会像这样实例化它



 SampleClass obj = new SampleClass(); 
//obj.Paint(); //编译错误
IControl c =(IControl)obj;
c.Paint(); //在SampleClass上调用IControl.Paint。
ISurface s =(ISurface)obj;
s.Paint(); //在SampleClass上调用ISurface.Paint。





其中IControl和ISurface是接口,paint是SampleClass中定义的继承这两个接口的方法



我的问题是

 IControl c =(IControl)obj; 

这里他们也创建了一个IControl实例

所以可以实例化接口吗?

请指导我..

解决方案







不,他们创建对实现接口的对象的引用。

:)

I have Read An interface cannot be instantiated directly in MSDN

but there only while giving an example they are instantiating it like this

SampleClass obj = new SampleClass();
//obj.Paint();  // Compiler error.
IControl c = (IControl)obj;
c.Paint();  // Calls IControl.Paint on SampleClass.
ISurface s = (ISurface)obj;
s.Paint(); // Calls ISurface.Paint on SampleClass. 



where IControl and ISurface are interfaces and paint is method which is defined in SampleClass which inherits these two interface

My question is

IControl c = (IControl)obj;

here also they are creating an instance of IControl
so wheter interface can be instantiated or not??
please guide me..

解决方案





No, they create a reference to an object implementing the interface.
:)


这篇关于是否可以实例化接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 05:49