做接口变量的值类型和引用类型的语义?
Do interface variables have value-type or reference-type semantics?
接口是由类型实现的,这些类型或者是值类型或引用类型。很显然,无论是 INT
和字符串
实施 IComparable的
和 INT
是值类型,而字符串
是引用类型。但对于这样的:
Interfaces are implemented by types, and those types are either value types or reference types. Obviously, both int
and string
implement IComparable
, and int
is a value type, and string
is a reference type. But what about this:
IComparable x = 42;
IComparable y = "Hello, World!";
(我试图回答的问题是:presumably删除,因为它要求的接口是否被存储在堆栈或堆中的,正如大家应该都知道,这是更有建设性的思考价值之间的差异在它们的语义,而不是他们的执行方面引用类型。对于讨论,请参阅埃里克利珀的栈是一个实现细节。)
通常情况下,按照现有的答案,这是引用类型和需要拳;有一个例外,虽然(是不是总是存在?)。在一个通用的方法以其中,
的约束,也可以是的两个的:
Usually, as per the existing answers, it is a reference-type and requires boxing; there is an exception though (isn't there always?). In a generic method with a where
constraint, it can be both:
void Foo<T>(T obj) where T : ISomeInterface {
obj.SomeMethod();
}
这是一个受限的操作,并没有盒装的即使的是一个值类型。这是通过constrained.相反,JIT进行操作的虚拟呼叫的引用类型,和静态调用的值类型。无拳。
This is a constrained operation, and is not boxed even if it is a value-type. This is achieved via constrained
. Instead, the JIT performs the operation as virtual-call for reference-types, and static-call for value-types. No boxing.