Closed. This question is off-topic。它当前不接受答案。
想改善这个问题吗? Update the question,所以它是on-topic,用于堆栈溢出。
6年前关闭。
如果实例化了一个类,它将创建一个对象。内存将分配给实例。如果接口实例化会怎样?接口是否有构造函数?它是否创建接口对象?是否将内存分配到接口对象
上面的线会产生什么?
现在,您可以创建
现在,您可以将其强制转换回原始对象,但仍然只有一个对象(或与您
想改善这个问题吗? Update the question,所以它是on-topic,用于堆栈溢出。
6年前关闭。
如果实例化了一个类,它将创建一个对象。内存将分配给实例。如果接口实例化会怎样?接口是否有构造函数?它是否创建接口对象?是否将内存分配到接口对象
interface IInteface {}
class Test : IInterface{}
IInterface ex1 = new Test();
上面的线会产生什么?
最佳答案
接口没有构造函数,因此不能自己创建。
将对象分配给变量(包括接口类型的变量)不会创建新对象,它只是对同一对象的另一个引用。
class DerivedWithInterface: Base, IEnumerable {}
现在,您可以创建
DerivedWithInterface
类的实例并分配给任何基类/接口的变量,但是只有new
会创建一个对象: DerivedWithInterface item = new DerivedWithInterface();
IEnumerable asEnumerable = item; // asEnumerable is the same object as create before
Base asBase = item;
现在,您可以将其强制转换回原始对象,但仍然只有一个对象(或与您
new
一样多的对象): IEnumerable asEnumerableItem = new DerivedWithInterface();
DerivedWithInterface itemViaCast = (DerivedWithInterface)asEnumerableItem;
asEnumerableItem
和itemViaCast
都引用和相同的单个实例,并且对象的类型为asEnumerableItem
关于c# - 如果接口(interface)由类实现,接口(interface)会创建对象吗? ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/19761447/