C# 将对象设置为 null
本文关键字:null 设置 对象 | 更新日期: 2023-09-27 18:30:36
我想将一个对象设置为 null,以便我可以"消费"它。在Java中,我们有这个。
//In some function/object
Vector3 position = new Vector3();
//In some loop.
if(position != null){
consumePositionAsForce(position);
position = null;
}
我知道在 C# 中,如果您使用的是基元类型,则必须对对象进行"装箱"和"取消装箱",我找不到任何关于可为空值类型的文档。
我正在尝试在 C# 中做同样的事情,但我收到有关类型转换的错误/警告。就像我不能设置 Vector3 = null 一样。
可以使用可为空的类型来执行此操作:
Vector3? vector = null;
并从某个地方分配其值:
position = new Vector3();
然后,您可以轻松地将其与null
进行比较,就像比较引用类型对象一样:
if(position != null) //or position.HasValue if you want
{
//...
}
验证它不是null
后,要访问Vector3
值,您应该使用 position.Value
。
你能把它声明为一个可为空的 Vector3 (Vector3?)吗?
Vector3? position = null;
这是我的第一个建议。或者,您可以将其设置为 Vector3.Zero,但我不太喜欢这个想法。
我相当确定 Vector3 是一种值类型,而不是引用类型,因此如果不明确将其声明为可为空的 Vector3,则无法为其分配 null。
Nullable<T>
具有可为 null 的值类型,其中 T
是struct
(primite 类型)或在后面添加 ?
作为类型的前缀。有了这个,你可以为sample设置一个int,一个Vector,或Vector3d结构为空,对于sample:
Vector? vector2d = null;
Vector3d? vector3d = null;
当您具有可为 null 的类型时,您有两个新属性,一个是 HasValue
返回一个 bool
值,指示对象是否存在有效值,Value
返回实际值(对于int?
返回int
)。你可以使用这样的东西:
// get a structure from a method which can return null
Vector3d? vector3d = GetVector();
// check if it has a value
if (vector3d.HasValue)
{
// use Vector3d
int x = vector3d.Value.X;
}
实际上,Nullable<T>
类尝试将值类型封装为引用类型,以给人一种可以为值类型设置 null 的印象。
我想你知道,但我建议你阅读更多关于装箱和拆箱的信息。
使用 Vector3?
(可为空的 Vector3) 而不是 Vector3
。
不能将值类型设置为 null。
由于 Vector3 是一个结构(这是一种值类型),因此您无法按原样将其设置为 null。
您可以使用可为空的类型,如下所示:
Vector3? position = null;
但是当您想在寻找常规 Vector3 的函数中使用它时,这将需要将其转换为 Vector3。
Vector3 是一个结构体,因此不可为空或可丢弃。您可以使用
Vector3? position = null;
或者你可以像这样改变它:
class Program
{
static void Main(string[] args)
{
using (Vector3 position = new Vector3())
{
//In some loop
consumePositionAsForce(position);
}
}
}
struct Vector3 : IDisposable
{
//Whatever you want to do here
}
该结构现在是一次性的,因此您可以在 using 语句中使用它。这将在使用后杀死对象。这比 null 更好,因为您不会使事情过于复杂,也不必担心错过 null 检查或事件内存中未释放的对象。