为什么可以进行接口变量实例化? [英] Why is interface variable instantiation possible?

查看:69
本文介绍了为什么可以进行接口变量实例化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

据我所知,接口无法实例化.

As far as I know, interfaces cannot be instantiated.

如果是这样,为什么下面的代码可以编译和执行?它允许您创建一个变量接口.为什么会这样?

If this is true, why does the below code compile and execute? It allows you to create a variable interface. Why is this possible?

接口:

public interface IDynamicCode<out TCodeOut>
{        
    object DynamicClassInstance { get; set; }
    TCodeOut Execute(string value = "");
}

InCode:

var x = new IDynamicCode<string>[10];

结果:

更新:

它仅在声明数组时发生.没有一个实例.

It only happens when array declared. Not a single instance.

推荐答案

您不是实例化一个接口,而是实例化该接口的数组.

You're not instantiating an interface, but an array of that interface.

您可以将实现 IDynamicCode< string> 的任何类的实例分配给该数组.假设您有公共类Foo:IDynamicCode< string>{} ,您可以实例化该实例并将其分配给该数组的元素:

You can assign an instance of any class that implements IDynamicCode<string> to that array. Say you have public class Foo : IDynamicCode<string> { }, you can instantiate that and assign it to an element of that array:

var x = new IDynamicCode<string>[10];
x[5] = new Foo();

实例化接口将无法编译:

Instantiating the interface would not compile:

var bar = new IDynamicCode<string>();

这篇关于为什么可以进行接口变量实例化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆