Tom*_*mer 11 c# mstest nullable-reference-types
MSTest 提供了一个[ClassInitialize]属性,可以将其放置在static方法上以提供一次性初始化。
假设我在测试类中有一个静态成员,我希望在这样的[ClassInitialize]方法中初始化它。我如何标记它不可为空?
例如,考虑以下代码:
private static Database _database;
[ClassInitialize]
public static void InitializeClass(TestContext testContext)
{
_database = new Database();
}
Run Code Online (Sandbox Code Playgroud)
使用#nullable enable,我得到一个非常容易理解的警告:CS8618 Non-nullable field '_database' must contain a non-null value when exiting constructor. Consider declaring the field as nullable.
我可以将初始化移至构造函数(但每个测试方法都会发生这种情况)。我可以使用 null-forgiving 运算符 ( !)。是否有更好的选项来标记_database不为空?
小智 5
在这种情况下我更喜欢使用空宽恕。具体来说,您可以只设置您知道将填充的属性,但编译器无法使用null!.
例如:
private static Database _database = null!;
Run Code Online (Sandbox Code Playgroud)