C# 类不再可以为空了吗?

标签 c# .net visual-studio

在 .NET 6.0 中使用 C# 我遇到了警告“无法将 null 文字转换为不可为 null 的引用类型”。我认为类可以为空并且能够设置为空...

这会产生警告:

    public class Foo
    {
        public string Name { get; set; }

        public Foo()
        {
            Name = "";
        }
    }

    public class Bar
    {
        public Foo fooClass;

        public Bar()
        {
            // Because I don't want to set it as anything yet.
            fooClass = null;
        }

        public void FooBarInit()
        {
            fooClass = new Foo();
        }
    }

但是这样做没有给我任何警告

    public class Foo
    {
        public string Name { get; set; }

        public Foo()
        {
            Name = "";
        }
    }

    public class Bar
    {
        public Foo? fooClass;

        public Bar()
        {
            // Because I don't want to set it as anything yet.
            fooClass = null;
        }

        public void FooBarInit()
        {
            fooClass = new Foo();
        }
    }

但是现在让我们尝试在 Bar 内的 Foo 中使用 Name 变量

    public class Foo
    {
        public string Name { get; set; }

        public Foo()
        {
            Name = "";
        }
    }

    public class Bar
    {
        public Foo? fooClass;

        public Bar()
        {
            // Because I don't want to set it as anything yet.
            fooClass = null;
        }

        public void FooBarInit()
        {
            fooClass = new Foo();
        }

        public void FooBarTest()
        {
            Console.WriteLine(fooClass.Name); // Warning here which tells me fooClass maybe null
        }
    }

但是,如果没有先运行 FooBarInit,FooBarTest 将永远不会运行。所以它永远不会为 null,如果是,之后我会遇到错误处理情况。

我的问题是,为什么我必须将类设置为允许 null,而它们本应接受 null?

如果我使用“?”在声明一个类之后...我现在必须检查它是否为空...任何时候我想调用那个类,它都会让我的代码看起来很糟糕。有任何修复或关闭它的能力吗?

最佳答案

尽管这是一个非常好的功能,您仍然可以通过将 .csproj 中的 Nullable 属性的值更改为 disable 来禁用它文件:

  <PropertyGroup>
    ...
    <Nullable>disable</Nullable>
    ...
  </PropertyGroup>

关于C# 类不再可以为空了吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74062153/

相关文章:

c# - Windows 事件日志中的这个条目是什么意思?

c# - ServiceStack 可以通过 System.DateTime 值进行查询吗?

.net - 是否可以从控制台应用程序使用 VSO Application Insights?

由 C# 网络发现

c# - Summernote 和 MVC c# 中的表单提交

c# - OleDbConnection.Open() 仅在一个项目中引发异常,相同的代码适用于其他项目

c# - devexpress 进度条 performstep 方法不显示

C++:使用 Visual Studio 编译器时的常量指针

c# - 在 Visual Studio 中获取 C# 类的所有接口(interface)

c# - WP8 项目 : The "CompileXaml" task failed unexpectedly