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

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

问题描述

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

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天全站免登陆