gpt4 book ai didi

asp.net-core - 如何在 aspnetcore razor View 页面 (.cshtml) 中启用#nullable

转载 作者:行者123 更新时间:2023-12-05 02:04:11 24 4
gpt4 key购买 nike

可能重复,但我一直找不到任何关于此的内容。

我有一个 asp.net core MVC 项目,它通过 Razor 使用普通 View 。

我有一些具有可为空引用类型的 ViewModel 对象,我正在使用 C# 8 空安全功能来适本地标记这些对象(例如 string?Name)

我的问题是,当我在 cshtml 文件中使用这些变量作为强类型模型时,没有应用 null-safety,因为我没有为该文件启用它。

如果它是一个 .cs 文件,我会在顶部粘贴 #nullable enable,但是我可以为 Razor 页面做些什么呢?


更新以澄清:如果可能的话,我希望在整个 razor 文件中的所有 @code block 上都出现空安全警告。 Tân's answer显示了如何为特定 block 启用它,但我喜欢这样的东西

<span>@Model.Name.ToUpper()</span>

具体来说,我想在 Name.ToUpper() 上发出警告,因为 Name 可以为 null 而我没有使用 ?调用 ToUpper 时的运算符

最佳答案

你的问题中没有足够的信息来说明你需要做什么(例如:添加一些包,删除一些包......)

但默认情况下,Razor syntax支持 #nullable ,您可以在 @{} block 中使用它。

例子:

@{
#nullable enable
string name1 = User.Identity.Name.ToLower();
#nullable disable

// compiler won't complain anything here...
string name2 = User.Identity.Name.ToLower();
}

测试:

1

我的 csproj 文件是我用来测试的:

<Project Sdk="Microsoft.NET.Sdk.Web">

<PropertyGroup>
<TargetFramework>netcoreapp3.1</TargetFramework>
</PropertyGroup>

</Project>

关于asp.net-core - 如何在 aspnetcore razor View 页面 (.cshtml) 中启用#nullable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64637280/

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