gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 00:15:06 28 4
gpt4 key购买 nike

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

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

这是我的构造函数:

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" );
}

我确实收到了 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>

最佳答案

可空引用类型仅用于编译时静态分析,如 docs状态:

Nullable reference types aren't new class types, but rather annotations on existing reference types. The compiler uses those annotations to help you find potential null reference errors in your code. There's no runtime difference between a non-nullable reference type and a nullable reference type. The compiler doesn't add any runtime checking for non-nullable reference types. The benefits are in the compile-time analysis. The compiler generates warnings that help you find and fix potential null errors in your code. You declare your intent, and the compiler warns you when your code violates that intent.

关于c# - 为什么构造函数中的空字符串参数不会引发异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64471533/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com