为什么在.NET参考类型的接口? [英] Why are interfaces in .Net reference types?

查看:226
本文介绍了为什么在.NET参考类型的接口?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么接口引用类型?据我了解,接口是类(或结构)之间的契约,那么,为什么它是一个类型的呢?我本来以为这既不是值类型或引用类型。

Why are interfaces reference types? As far as I understand, an interface is a contract between classes (or structs), so why is it a type at all? I would have thought it is neither a value type or a reference type.

推荐答案

要被视为一个结构的编译器必须知道的在编译时什么具体类型,预留的右侧空间叠加。这意味着即使结构实现的IFoo ,然后用:

To be treated as a struct the compiler must know at compile time what the concrete type is, to reserve the right space on the stack. This means that even if a struct implements IFoo, then with:

var ms = new MyStruct();
IFoo foo = ms;

然后分配到是装箱操作。你可以说编译器应该发现,它永远都只有一个foo和使用constainedOP code,但是的在一般情况下的(多指配等),这是不可能的(我会大胆地猜测,这会打击停机问题)。

then the assignment to foo is a boxing operation. You could say "the compiler should spot that it is only ever a foo and use the 'constained' opcode", but in the general case (with multiple assignments to foo etc) this isn't possible (I would hazard a guess that it will hit the "halting problem").

还有虚拟VS静态调用的问题,但约束OP code的工作解决这一问题。

There is also an issue of virtual vs static call, but the "constrained" opcode works around that.

基本上,界面的任何使用必须始终被视为参考

Basically, any usage of the interface must always be treated as a reference.

有一个例外:通用约束

如果您有

static void DoBar<T>(T target) where T : IFoo {
    target.Bar();
}

下面的方法一次即时编译每个值类型,因此需要 T栈空间 知道;调用酒吧是有限的,并根据需要可以是虚拟或静态自动。

here the method is JITted once per value-type, so the stack-space needed for T is known; the call to Bar is "constrained" and can be virtual or static automatically as needed.

这篇关于为什么在.NET参考类型的接口?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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