简体   繁体   English

Nullable struct vs class

[英]Nullable struct vs class

I have a simple struct which contains two fields; 我有一个包含两个字段的简单结构; one stores an object and the other stores a DateTime. 一个存储一个对象,另一个存储DateTime。 I did this because I wanted to store objects in a Dictionary but with a DateTime stamp as well. 我这样做是因为我想在Dictionary中存储对象,但也有DateTime标记。

I've got a method which returns my structure, and I've now decided the method should also be able to return null, so I made my structure nullable. 我有一个返回我的结构的方法,我现在已经确定该方法也应该能够返回null,所以我使我的结构可以为空。 I'm now wondering if I should just make my structure a class so it's a reference type? 我现在想知道我是否应该让我的结构成为一个类,所以它是一个引用类型?

In this case, yes, it's probably clearer to make your structure a class. 在这种情况下,是的,使您的结构成为一个类可能更清晰。

As far as justification goes, you're essentially creating a specialized Tuple . 至于理由,你实际上是在创建一个专门的Tuple It's interesting to note that the library designers have opted to make the .Net 4 Tuple a class rather than a struct. 值得注意的是,图书馆设计师选择将.Net 4 Tuple作为一个类而不是一个结构。 (That page is the tuple creator and links to the various tuple instance classes) (该页面是元组创建者并链接到各种元组实例类)

Either should be fine, in reality (as long as the struct is immutable). 实际上要么是好的(只要struct是不可变的)。 A DateTime and a reference shouldn't be enough to make it oversized. DateTime和引用不足以使其超大。

I assume you are using it as the value (not the key ) in the dictionary? 我假设你使用它作为字典中的 (而不是 )? If used as the key you would need to override Equals and GetHashCode() , regardless of struct vs class . 如果用作键,则需要重写EqualsGetHashCode() ,而不管struct vs class

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM