结构可以包含引用类型的字段 [英] Can structs contain fields of reference types

查看:200
本文介绍了结构可以包含引用类型的字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

灿结构包含引用类型的字段?如果他们可以,这是一个不好的做法?

Can structs contain fields of reference types? And if they can is this a bad practice?

推荐答案

是的,他们可以。这是个好主意吗?嗯,这取决于具体情况。我个人很少在第一时间创建自己的结构......我会像对待任何新的用户定义的结构有一定程度的怀疑。我并不是说,它的的总是的错误的选项,只是它需要一个多类明确的说法。

Yes, they can. Is it a good idea? Well, that depends on the situation. Personally I rarely create my own structs in the first place... I would treat any new user-defined struct with a certain degree of scepticism. I'm not suggesting that it's always the wrong option, just that it needs more of a clear argument than a class.

这将是一个糟糕的主意,一个结构有一个可变对象,虽然引用......否则,你可以拥有它的两个值看的独立,但都没有:

It would be a bad idea for a struct to have a reference to a mutable object though... otherwise you can have two values which look independent but aren't:

MyValueType foo = ...;
MyValueType bar = foo; // Value type, hence copy...

foo.List.Add("x");
// Eek, bar's list has now changed too!

可变结构是邪恶的。与以可变类型的引用不可变的结构是不同的方式悄悄的罪恶。

Mutable structs are evil. Immutable structs with references to mutable types are sneakily evil in different ways.

这篇关于结构可以包含引用类型的字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆