开发者

Why are interfaces in .Net reference types?

开发者 https://www.devze.com 2023-02-03 01:38 出处:网络
Why are interfaces reference types? As far as I un开发者_StackOverflowderstand, an interface is a contract between classes (or structs), so why is it a type at all? I would have thought it is neither

Why are interfaces reference types? As far as I un开发者_StackOverflowderstand, 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.


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;

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.

If you have

static void DoBar<T>(T target) where T : IFoo {
    target.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.


They're reference types because value types have a fixed size at compile-time, so that they can be allocated on the stack. Reference types are pointers, so the pointers are constant-size but they can point to memory of any size.

0

精彩评论

暂无评论...
验证码 换一张
取 消