![](/img/trans.png)
[英]Setting a Value to a field inside an object “Only” if the Value is not null in C#
[英]C# setting object as null
我想将一个对象设置为null,以便可以“消费”各种对象。 在Java中,我们有这个。
//In some function/object
Vector3 position = new Vector3();
//In some loop.
if(position != null){
consumePositionAsForce(position);
position = null;
}
我知道在C#中,如果您使用的是基本类型buut,则必须将对象“装箱”并“取消装箱”,我找不到关于可空值类型的任何文档。
我正在尝试在C#中执行相同的操作,但是却收到有关类型转换的错误/警告。 如我不能设置Vector3 = null。
您可以将其声明为可为空的Vector3(Vector3吗?)?
Vector3? position = null;
那是我的第一个建议。 另外,您可以将其设置为Vector3.Zero,但我真的不喜欢这个想法。
我相当确定Vector3是一个值类型,而不是引用类型,因此您不能在未显式声明为可为空的Vector3的情况下为其分配null。
您可以使用Nullable<T>
来具有可为空的值类型,其中T
是一个struct
(基本类型)或添加一个?
之后作为类型的前缀。 这样,您可以将样本的int, Vector或Vector3d结构设置为可空的样本:
Vector? vector2d = null;
Vector3d? vector3d = null;
当您具有可为空的类型时,将具有两个新属性,即HasValue
返回一个bool
值,该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是一个结构,因此不能为null或可抛弃。 您可以使用
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语句中使用它。 使用后将杀死该物体。 这比空值更好,因为您不会使事情复杂化,也不必担心丢失空值检查或发生内存中未处理的对象的事件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.