c# - 当前上下文错误中不存在,但它应该存在 - ASP.NET c#

标签 c# asp.net

代码如下:

for (int i = 0; i < Model.Count; i++)
{
    Writer.WriteBeginTag("li");
    if (i % 2 == 1)
    {
            string myVar  = "even ";
    }
    if ((i+1) % 3 == 0)
    {
        myVar += "third";
    }
    Writer.WriteAttribute("class", ""); // I want to use myVar here
    Writer.Write(HtmlTextWriter.TagRightChar);
    Writer.WriteEndTag("li");
}

我对 .NET 或 C# 不是很熟悉。我在第二个 myVar 上收到错误 The name "myVar"does not exist in the current context。如果我注释掉这一行,那么我会在第一个 myVar 上收到一条消息 The variable "myVar"is assigned but its value is never used.。我真的不明白这如何或为什么会超出上下文/范围。

有什么想法吗?

最佳答案

您正在第一个 if 语句的范围内创建变量 myVar,因此它在第二个语句中不可用。您需要事先创建它:

string myVar = "";
if(...)
{
  //use of myVar
}
if(...)
{
 //use of myVar
}

关于c# - 当前上下文错误中不存在,但它应该存在 - ASP.NET c#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5637375/

相关文章:

.net - 允许在 URL 中使用星号

javascript - 谷歌地图搜索框功能在模态窗口中不起作用

asp.net - 为什么默认情况下ViewState不存储在服务器上?

c# - 在 Windows Phone 8 应用程序中添加 Font Awesome

c# - 使用 PowerShell 和模块化 GUI 吗?

c# - 两个物体在什么增量时间发生碰撞?

c# - 计算百分比时抛出 OverflowException

c# - 在模拟另一个域帐户时进行调试

asp.net - 是否有任何 .NET 标准可以处理本地化并允许用户自定义文本?

asp.net - 更新面板问题