是否可以实例化接口 [英] whether an interface can be instantiated
问题描述
我有阅读界面无法直接在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实例
所以可以实例化接口吗?
请指导我..
不是真的确定您的问题是什么,但该底线显示SampleClass实例被转换为IControl,然后分配给IControl变量。实际上,编译器足够聪明,可以知道类何时实现接口,因此不需要显式转换。您可以写:
IControl c = obj;
说接口不能直接是正确的实例化,因为它们不是真正的类(它们只是某些类必须实现的接口)。然后,您可以创建实现该接口的类的实例,然后将该实例分配给接口类型的变量。例如,你也可以这样做:
IControl c = new SampleClass();
c.Paint();
现在,如果你想将它分配给一个ISurface变量,你必须明确地转换它:
ISurface s =(ISurface)c;
我建议你做一些阅读(一本书或一些在线教程)面向对象的编程,可能与C#有关。
IControl c
实际上不是的实例IControl
,但SampleClass的实例
已投放到IControl
。
nishuthegreat写道:我的问题是
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..
Not really sure what your question is, but that bottom line shows the SampleClass instance being casted as an IControl and then assigned to an IControl variable. Actually, the compiler is smart enough to know when a class implements an interface, so the explicit cast is not necessary. You could just write:
IControl c = obj;
It is correct to say interfaces cannot be directly instantiated, as they are not really classes (they are just interfaces that some class must implement). You can then create an instance of a class that implements the interface, then assign that instance to a variable of the interface type. For example, you could have also done this:
IControl c = new SampleClass(); c.Paint();
Now, if you wanted to assign that to an ISurface variable, you would have to explicitly cast it:
ISurface s = (ISurface)c;
I recommend you do some reading (a book or some tutorials online) about object oriented programming, perhaps specifically as it relates to C#.
IControl c
is not really an instance ofIControl
, but an instance ofSampleClass
casted toIControl
.
nishuthegreat wrote:My question is
IControl c = (IControl)obj;
here also they are creating an instance of IControl
so wheter interface can be instantiated or not??
No, they create a reference to an object implementing the interface.
:)
这篇关于是否可以实例化接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!