开发者

Does not exist in current context error, but it should - ASP.NET c#

开发者 https://www.devze.com 2023-02-25 14:02 出处:网络
Here is the code: for (int i = 0; i < Model.Count; i++) { Writer.WriteBeginTag(\"li\"); if (i % 2 == 1)

Here is the code:

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

I'm not all that familiar with .NET or C#. I get an error The name "myVar" does not exist in the current context on the second myVar. If I comment this line out, I then have a message The variable "myVar" is assigned but its value is never used. on the first 开发者_C百科myVar. I don't really understand how or why this would be out of context/scope.

Any ideas?


You are creating the variable myVar in the scope of the first if statement, thus it isn't available in second one. You need to create it beforehand:

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


myVar only exists inside your if.

You need to move the declaration to the body of the loop.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号