我有一个类,例如这个:
public class Foo
{
public string Bar { get; init; }
public IImmutableSet<int> Baz { get; init; }
}
当我这样写的时候,我得到一个编译器警告
Non-nullable property 'Bar' must contain a non-null value when exiting constructor. Consider declaring the property as nullable. csharp(CS8618)
有很多内容解决这个问题(例如 here ),但据我所知,它只是关于如何通过设置默认值或使用 "假默认值”,如 null!
。
但在我的例子中,默认值没有意义。 相反,我想告诉编译器必须显式设置这些属性,这样如果在使用对象之前没有设置任何属性,编译器就会提示。就像未分配的局部变量的情况一样:
这可能吗?如果可能,怎么做?
我知道我可以只定义一个带参数的构造函数,因此使用该构造函数是创建新实例的唯一方法。但是因为我有很多像上面这样的类,我需要写很多额外的代码(即构造函数)。如果有一种“必须初始化”标志,我的代码的读者也会更清楚。
最佳答案
我认为 get;
只有带有构造函数的属性才是可行的方法。
public class C
{
public C(string a)
{
A = a;
}
public string A { get; }
}
I would need to write quite of lot of extra code (i.e. the constructors).
如今创建构造函数非常容易。它需要:
微软怎么说?
1。 Working with Nullable Reference Types
在Working with Nullable Reference Types在不可为空的属性和初始化中显示了 3 个选项:
一个。构造函数
Constructor binding is a useful technique to ensure that your non-nullable properties are initialized:
b。可为空的支持字段
Unfortunately, in some scenarios constructor binding isn't an option; navigation properties, for example, cannot be initialized in this way. (...) One way to deal with these scenarios, is to have a non-nullable property with a nullable backing field: C#
private Address? _shippingAddress; public Address ShippingAddress { set => _shippingAddress = value; get => _shippingAddress ?? throw new InvalidOperationException("Uninitialized property: " + > nameof(ShippingAddress)); }
c。强制初始化为 null!
作为一种更简洁的替代方法,可以借助允许空值的运算符 (!) 将属性简单地初始化为空值:
C#
public Product Product { get; set; } = null!;
An actual null value will never be observed except as a result of a programming bug, e.g. accessing the navigation property without properly loading the related entity beforehand.
2。 Learn techniques to resolve nullable warnings
在Learn techniques to resolve nullable warnings再次没有 get 的例子; init;
属性,文章提出了两个处理警告的选项:
- 构造器
- 初始化为
null!;
to indicate that a member is initialized in other code.
3。 Attributes for null-state static analysis interpreted by the C# compiler
对于更复杂的场景,可能值得一看 Attributes for null-state static analysis interpreted by the C# compiler并使用一些可用的属性。不过,我认为这不是日常代码的路径。
关于c# - 如何告诉编译器必须初始化属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71288394/