String不当前环境的存在 - C# [英] String does not exist in current context - C#
本文介绍了String不当前环境的存在 - C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
出于某种原因,我的字符串:FIRSTLINE不被另一种方法回升。这背后的理由?
公共静态无效测试1()
{
..
的String [] = linesw obj1.ReadToEnd()斯普利特(新的char [] {'\\\
'});
串FIRSTLINE = linesw [1];
..
}
公共静态无效测试2()
{
..
HttpWebRequest的要求=(HttpWebRequest的)WebRequest.Create(第一行);
..
}
解决方案
FIRSTLINE
是一个局部变量,并在不同的方法使用时,超出范围。 。推动它作为一个类变量或作为替代参数
作为类变量:
私有静态字符串FIRSTLINE =的String.Empty; //类变量
公共静态无效测试1()
{
..
的String [] = linesw obj1.ReadToEnd()。斯普利特(新的char [] {'\\\
'});
FIRSTLINE = linesw [1];
..
}
公共静态无效测试2()
{
..
HttpWebRequest的要求=(HttpWebRequest的)WebRequest.Create(第一行);
..
}
$ B $调用当b
或者,作为参数 TEST2()
从 test1的()
:
公共静态无效测试1()
{
..
的String [] = linesw obj1.ReadToEnd()。斯普利特(新的char [] { '\\\
'});
串FIRSTLINE = linesw [1];
测试2(FIRSTLINE);
..
}
公共静态无效测试2(字符串FIRSTLINE)...
For some reason my string: "firstline" is not being picked up in another method. What is the reasoning behind this?
public static void test1()
{
..
string[] linesw = obj1.ReadToEnd().Split(new char[] { '\n' });
string firstline = linesw[1];
..
}
public static void test2()
{
..
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(firstline);
..
}
解决方案
firstline
is a local variable and goes out of scope when used in a different method. Promote it as a class variable or as a parameter instead.
As class variable:
private static string firstline = String.Empty; // class variable
public static void test1()
{
..
string[] linesw = obj1.ReadToEnd().Split(new char[] { '\n' });
firstline = linesw[1];
..
}
public static void test2()
{
..
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(firstline);
..
}
Or, as parameter when calling test2()
from test1()
:
public static void test1()
{
..
string[] linesw = obj1.ReadToEnd().Split(new char[] { '\n' });
string firstline = linesw[1];
test2(firstline);
..
}
public static void test2(string firstline)...
这篇关于String不当前环境的存在 - C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文