为什么接口是 .Net 引用类型? [英] Why are interfaces in .Net reference types?

查看:30
本文介绍了为什么接口是 .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 的赋值是一个装箱操作.您可以说编译器应该发现它只是一个 foo 并使用‘包含’操作码",但是在一般情况下(对 foo 等进行多次赋值)) 这是不可能的(我敢猜测它会遇到停机问题").

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").

还有一个虚拟调用与静态调用的问题,但受约束的"操作码可以解决这个问题.

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.

对此有一个例外:通用约束.

There is one exception to this: generic constraints.

如果你有

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

这里的方法对每个值类型进行了一次 JIT,因此 T 所需的堆栈空间是已知的;对 Bar 的调用是受约束的",可以根据需要自动为虚拟或静态.

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天全站免登陆