【发布时间】:2013-03-04 17:21:37
【问题描述】:
我最近遇到了这个 Stackoverflow 问题:When to use struct?
里面有一个回答有点深奥:
另外,要意识到当一个结构实现一个接口时——如 Enumerator 确实 - 并被强制转换为实现的类型,即 struct 成为引用类型并移动到堆中。内部的 Dictionary 类,Enumerator 仍然是值类型。然而,尽快 当方法调用 GetEnumerator() 时,引用类型的 IEnumerator 是 返回。
这究竟是什么意思?
如果我有类似的东西
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!?
将值类型结构视为引用类型的详细语义究竟是什么?
【问题讨论】:
-
我想你自己回答了这个问题——“结构变成了引用类型并被移到了堆中”
-
我不知道你的例子中的 Foobar 是什么...
-
@JoshE 所以两个引用会指向同一个东西?如果值类型发生变化怎么办?是否有任何 MSDN 文档或解释这一点的东西?
-
它被称为拳击,MSDN 上有很多文档。 msdn.microsoft.com/en-us/library/yz2be5wk.aspx你发布的代码测试了吗?
-
想一想:如果我尝试
Foo foo = b.Biz;,我会得到一个“无法将类型 IFoo 隐式转换为 Foo”的编译错误 - 你必须显式地装箱/拆箱,这就是foo = null的原因和方式值类型不能是null(指向堆上的值类型的指针 = null)
标签: c# .net struct value-type boxing