简体   繁体   English

C#列表集合在方法之外失去其价值

[英]C# list collection loses its value outside of method

I'm new to C# and the ASP.NET framework and can't seem to find an answer as to why the values added to a list collection in one method either disappear or can't be accessed in another method. 我是C#和ASP.NET框架的新手,似乎无法找到关于为什么在一种方法中添加到列表集合的值消失或无法在另一种方法中访问的答案。 If I print the contents of the list right after it is created, the values are returned, but the debugger says there's nothing in the list after the list has been created and accessed in a different method. 如果在创建列表后立即打印列表的内容,则会返回值,但是调试器会说在创建列表并以其他方法访问之后,列表中没有任何内容。

This is the class that is the datatype for the list: 此类是列表的数据类型:

class Letter
{
    public char Character { get; set; }
    public bool Guessed { get; set; }
}

This is the list being declared (the printing out at the end does work): 这是要声明的列表(最后的打印确实可行):

private List<Letter> currentWord = new List<Letter>();

This is the method creating the list: 这是创建列表的方法:

protected void CreateCurrentWordList()
    {
        char[] letterArray = computerChoice.ToCharArray();
        for (int i = 0; i < letterArray.Length; i++)
        {
            currentWord.Add(new Letter { Character = letterArray[i], Guessed = false });
        }
        string displayString = PrintCurrentWord();
        TestLabel.Text = displayString;
    }

And this is the code block in another method that can't access the values inserted into the list or where the list shows up as empty in the debugger: 这是另一种方法的代码块,该方法无法访问插入列表中的值,或者列表在调试器中显示为空:

foreach (Letter letter in currentWord)
            {
                if (letter.Character.ToString() == userGuess)
                {
                    letter.Guessed = true;
                    displayString += letter.Character.ToString();
                }                   
            }

Thanks for any help or direction to another post answering this question. 感谢您对其他回答此问题的帮助或指导。

EDIT: Adding static keyword to list collection declaration seems to have solved the problem. 编辑:向列表集合声明中添加static关键字似乎已经解决了该问题。 Thanks PiJei! 谢谢皮杰!

It could be for many reasons: 原因可能有很多:

  1. You have two or more objects instantiated and one of them has no values in it. 您有两个或多个实例化的对象,其中之一没有任何值。
  2. You are using the block code of the method that can't access the values before adding values to the list. 您正在使用在将值添加到列表之前无法访问值的方法的代码块。
  3. You postback the page losing the data in the list. 您回发页面,丢失列表中的数据。

I would try storing currentWord in a ViewState["myList"] to see if it has values after some requests. 我会尝试将currentWord存储在ViewState [“ myList”]中,以查看某些请求后是否具有值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM