c# - ASP.net 网页错误 Use of unassigned local variable 'some'

标签 c# asp.net razor

我有这样的 Razor 代码

bool some;

if (IsPost == false)
{

 some = True

}

然后 html

<h1>@some.ToString()</h1>

当我运行它时它得到了我的错误 使用未分配的局部变量“some”

谁能解释一下为什么? razor 代码不是先执行再执行 html 吗?

最佳答案

为您的变量分配一些值。

bool some  = false;

could anyone explain why? doesn't razor code executes first and then html?

它与 Razor 或 HTML 执行优先级没有任何关系。考虑以下简单的 C# 示例:

bool some;
Console.WriteLine(some);

您正在尝试编写尚未分配任何值的一些。与 @some.ToString() 的情况类似,您没有为其分配任何值,编译器无法确定它是否会获取 if< 中的值 语句。

您还可以:

bool some = default(bool); //same as false for bool

你也可以在 else 部分给 some 赋值,比如:

bool some;
bool IsPost = true;
if (IsPost == false)
{
    some = true;
}
else
{
    some = false;
}

现在编译器知道 some 将被分配一些值并且您的错误将消失。

不太确定,但看起来您正在尝试将 IsPost 的值切换一些,您可以这样做:

some = !IsPost;

关于c# - ASP.net 网页错误 Use of unassigned local variable 'some',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18903092/

相关文章:

c# - 在我看来,什么时候应该从数据库中查询,ASP.NET MVC

c# - mkbundle 生成的程序(来自 C# 程序)在 Ubuntu 上运行,但在 Redhat 上不起作用

c# - 如何使登录页面成为 ASP.NET MVC Web 应用程序中的启动页面?

c# - 使用 WebClient 或类似方法从 .NET Framework 2.0 ASP.NET 应用程序获取 Azure AD 访问 token

javascript - MVC 在暂停四秒后重定向到另一个页面

javascript - 使用 toastr.js 时 toastr 未定义

c# - 将列表分组为每组 X 项的组

c# - 数字到 bool 值的自动转换 - 从 Newtonsoft 迁移到 System.Text.Json

c# - 产品发布改了库名,新旧如何兼容?

javascript - 在javascript中返回带参数的消息