首页 > 解决方案 > 我应该使用 Nullables 还是结构的唯一值?

问题描述

我正在重构我的程序,从类切换到结构,以便从中获得更多性能。我需要一个值或方法来替换我的代码中的“null”。C# 提供了Nullable类型(即StructName?),但它看起来更像是一个用于包装其他类型的特殊类,而不是我可以信任以保持性能的某种特殊空值。

Node? temp = _closedList[_closedList.IndexOf(current)];
if (temp == null as Node) return null;
do {
    _path.Push(temp.Value);
    RecordState();
    temp = getNode(temp.Value.ParentPosition);
} while (temp.HasValue && temp.Value.Position != startNode.Position);

我的另一个可能更好的主意是创建一个表示“null”的特殊值,Int32.MaxValue对所有相关字段使用类似的东西,然后使用一个检查这些特殊值的 getter。据我所知,这听起来会保留性能,但看起来不会超级好。

Node temp = _closedList[_closedList.IndexOf(current)];
if (temp.IsNull) return null;
do {
    _path.Push(temp);
    RecordState();
    temp = getNode(temp.ParentPosition);
} while (!temp.IsNull && temp.Position != startNode.Position);

我已经查看了很多不同的消息来源,一个说 Nullables 很糟糕,另一个说它们很好,还有人建议使用独特的值作为替代。我应该怎么办?

注意:上面的代码没有经过测试,我只是编辑了我认为 Nullable/Null Value 实现可能看起来的样子。

标签: c#structnullnullablenullable-reference-types

解决方案


推荐阅读