在 .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/