小编raa*_*ndy的帖子

为什么构造函数中的空字符串参数不会引发异常?

我已经看过了,但无法弄清楚为什么当我启用了空引用类型时,当我在构造函数中为字符串参数传递空值时,我没有收到异常。

构造函数参数不会被视为不可为空吗?

这是我的构造函数:

public ApiClient( string baseUrl, string authorizationToken ) {

    string testString = null;
    _apiClientBaseUrl = baseUrl ?? throw new ArgumentNullException( $"{nameof(baseUrl)} cannot be null" );
    _authorizationToken = authorizationToken ?? throw new ArgumentNullException( $"{nameof(authorizationToken)} cannot be null" );
}
Run Code Online (Sandbox Code Playgroud)

我确实收到该string testString = null;行的错误。如果我删除编码的空测试,我可以为 2 个属性传入空值,并且不会出现任何错误。该对象将实例化得很好。

我在一个 .NET Core 3.1 项目中,在 .csproj 文件中:

<PropertyGroup>
    <TargetFramework>netcoreapp3.1</TargetFramework>
    <Nullable>enable</Nullable>
    <WarningsAsErrors>CS8600;CS8602;CS8603;CS8625</WarningsAsErrors>
    <TreatWarningsAsErrors>true</TreatWarningsAsErrors>
</PropertyGroup>
Run Code Online (Sandbox Code Playgroud)

c# .net-core nullable-reference-types

3
推荐指数
1
解决办法
105
查看次数

标签 统计

.net-core ×1

c# ×1

nullable-reference-types ×1