在当结构实现了接口会发生什么情况详细信息 [英] Details on what happens when a struct implements an interface
问题描述
我最近过这个#1问题就来了:何时使用结构在C#一>
I recently came across this Stackoverflow question: When to use struct in C#?
在它,它有一个答案说的东西有点深奥:
In it, it had an answer that said something a bit profound:
此外,意识到,当一个结构实现的接口 - 如 枚举器那样 - 并转换为所实施的类型,结构 成为基准的类型和移动到堆。内部的 Dictionary类,枚举仍然是值类型。然而,只要 作为一个方法调用的GetEnumerator(),引用类型的IEnumerator是 回来了。
In addition, realize that when a struct implements an interface - as Enumerator does - and is cast to that implemented type, the struct becomes a reference type and is moved to the heap. Internal to the Dictionary class, Enumerator is still a value type. However, as soon as a method calls GetEnumerator(), a reference-type IEnumerator is returned.
究竟是什么意思?
如果我有这样的事情
struct Foo : IFoo
{
public int Foobar;
}
class Bar
{
public IFoo Biz{get; set;} //assume this is Foo
}
...
var b=new Bar();
var f=b.Biz;
f.Foobar=123; //What would happen here
b.Biz.Foobar=567; //would this overwrite the above, or would it have no effect?
b.Biz=new Foo(); //and here!?
到底是什么价值型结构被视为一个引用类型的具体语义?
What exactly are the detailed semantics of a value-type structure being treated like a reference-type?
推荐答案
结构类型的每份报关单,真正宣告了运行中的两种类型:值类型,以及堆对象类型。但从外部code中的点,堆对象类型将表现得象一个类与字段和对应的值类型的方法。但从内部code点,堆型将表现为,虽然它有一个字段这
相应的值类型。
Every declaration of a structure type really declares two types within the Runtime: a value type, and a heap object type. From the point of view of external code, the heap object type will behave like a class with a fields and methods of the corresponding value type. From the point of view of internal code, the heap type will behave as though it has a field this
of the corresponding value type.
试图投值类型为引用类型(对象
,值类型
,枚举
,或任何接口类型)将产生其对应的堆对象类型的新实例,并返回一个对新的实例。如果尝试存储值类型转换为引用类型的存储位置,或者把它作为一个引用类型的参数同样的事情会发生。一旦值已被转换为一个堆对象,它的行为 - 但从外部code点 - 作为一个堆对象
Attempting to cast a value type to a reference type (Object
, ValueType
, Enum
, or any interface type) will generate a new instance of its corresponding heap object type, and return a reference to that new instance. The same thing will happen if one attempts to store a value type into a reference-type storage location, or pass it as a reference-type parameter. Once the value has been converted to a heap object, it will behave--from the point of view of external code--as a heap object.
其中可以没有首先被转换为一个堆对象的值的类型中使用的值的类型的实现,接口的唯一情况是当它通过为具有接口类型作为约束一个一般类型参数。在这种特定的情况,接口构件可以用在该值的类型实例,而其具有被第一转换为一个堆对象
The only situation in which a value type's implementation of an interface may be used without the value type first being converted to a heap object is when it's passed as a generic type parameter which has the interface type as a constraint. In that particular situation, interface members may be used on the value type instance without its having to be converted to a heap object first.
这篇关于在当结构实现了接口会发生什么情况详细信息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!