繁体   English   中英

为什么 C# 空值检查不适用于结构?

[英]Why doesn't C# null check work with structs?

我通常使用if (foo is not null)检查可空类型,然后我可以像使用非空类型一样使用foo 为什么这不适用于结构? 甚至! 运营商没有帮助。 这是一个错误还是我错过了什么? 最短的解决方法是什么?

Foo? foo = new Foo { a = "foo" }; 
if (foo is not null) {
    Console.WriteLine(foo.a);  // Works, prints "foo"
}

Bar? bar = new Bar { a = "bar" };
if (bar is not null) {
    Console.WriteLine(bar.a);  // Error: Bar? does not contain a definition for "a"
    Console.WriteLine(bar!.a); // Same error
}

class Foo {
    public string a;
}
struct Bar {
    public string a;
}

向后兼容。

可空值类型从 C# 2.0 开始存在,它们的实现方式不同于可空引用类型(自 C# 8.0 起)。

  • int? Nullable<int>的同义词,它是与int完全不同的类型。 有一些编译器魔法(提升的运算符)使其行为相似,但Nullable<int>具有int没有的成员( HasValueValue ),反之亦然( ToString(string) )。
  • string? 另一方面,是string类型,启用了额外的编译时检查。

int? 允许您访问底层int而无需使用.Value “解包”它会破坏大量现有代码。


但是,您可以使用模式匹配来创建具有基础类型的变量:

int? a = 3;      // implicit conversion from int to Nullable<int>

if (a is int b)
{
    // Use b to access the underlying int here.
}
else
{
    // a was null
}

结构是值类型,不能赋值为 null。 通过将结构声明为可为空,您可以将它们包装在 Nullable<T> 结构中。 在您的情况下,您应该检查 Nullable<Bar> 结构的 HasValue 和 Value 属性。

        Bar? bar = new Bar { a = "bar" };
        if (bar.HasValue)
        {
            Console.WriteLine(bar.Value.a);
            Console.WriteLine(bar.Value.a);
        }

结构是一种值类型,因此它永远不会为空。 您可以检查 struct 的默认值

暂无
暂无

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

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