C# - Variable does not exists in current context

三世轮回 提交于 2019-12-06 14:34:09

问题


I have a problem I can't seem to solve.

I created a class function called test and in the function I declared a variable. On the next line I fill the function with a string.

During debugging the variable does not get declared, my variable watcher in VS tells me that the variable does not exists in the current context.

Can you all help me solve this problem ?

Here is my code:

public void Test()
{
    string DirectoryPath;
    DirectoryPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.InternetCache);
}

回答1:


My guess is you're using a Release configuration - the optimizer may have removed the variable, as it's pointless other than for debugging. You assign it a value, but never read it. In a Debug configuration, I'd expect it to be fine (but possibly create a warning).

EDIT: Of course, this is assuming that you were in the Test() method that you couldn't see the variable. If Test() had already completed then Likurg's answer is probably more appropriate.




回答2:


If i'm not mistake you want to do this

    public class MyTest
    {
        string DirectoryPath = "";
        public void Test()
        {
            DirectoryPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.InternetCache);
        }
        public void UseString()
        {
            //Use DirectoryPath
        }
    }


来源:https://stackoverflow.com/questions/10141579/c-sharp-variable-does-not-exists-in-current-context

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!