C# 6.0 使用 Null 传播运算符检查局部变量或对象是否为 Null(不是字段)的方法
C# 6.0 Approach to Checking if Local Variable or Object is Null (not a field) Using the Null-propagation Operator
我知道使用新的 C# 6.0,您可以在以下简化示例中检查 null:
MyClass myClass = new MyClass();
string example = myClass?.someFieldInMyClass;
这是一种更简洁的检查空值的方法。太棒了!
我很好奇是否有办法使用 new 运算符检查传入的局部变量或参数是否为 null。因此,如果将参数传递给这样的方法:
public static void SomeMethod(mytype t)
{
AnotherClass.myfield = t;
}
有没有办法检查 t
是否为空?我一直在查看文档,但没有找到任何东西。
我正在寻找类似 Anotherclass.somefield = ?t;
的内容
是否期望您在通过之前检查它?我想这样做的原因是我传递了一个自定义类型,它是另一个 class 上的 属性。然后,我将另一个 class 设置为我传入的自定义 属性。
也许这只是代码味道,我愿意接受建议。
我不确定你想要完成什么,但如果你想避免覆盖
的值
AnotherClass.myfield
有了可能的 null t 那么你就可以这样做
AnotherClass.myfield = t ?? AnotherClass.myfield;
如果t不为null,那么它只会改变myfield的赋值,否则它会保持它之前的赋值(重新赋值)。
我知道使用新的 C# 6.0,您可以在以下简化示例中检查 null:
MyClass myClass = new MyClass();
string example = myClass?.someFieldInMyClass;
这是一种更简洁的检查空值的方法。太棒了!
我很好奇是否有办法使用 new 运算符检查传入的局部变量或参数是否为 null。因此,如果将参数传递给这样的方法:
public static void SomeMethod(mytype t)
{
AnotherClass.myfield = t;
}
有没有办法检查 t
是否为空?我一直在查看文档,但没有找到任何东西。
我正在寻找类似 Anotherclass.somefield = ?t;
是否期望您在通过之前检查它?我想这样做的原因是我传递了一个自定义类型,它是另一个 class 上的 属性。然后,我将另一个 class 设置为我传入的自定义 属性。
也许这只是代码味道,我愿意接受建议。
我不确定你想要完成什么,但如果你想避免覆盖
的值AnotherClass.myfield
有了可能的 null t 那么你就可以这样做
AnotherClass.myfield = t ?? AnotherClass.myfield;
如果t不为null,那么它只会改变myfield的赋值,否则它会保持它之前的赋值(重新赋值)。