我的功能有问题
public class PS3
{
public static void restoreAllClassesNames(string A, string B, string C/*, string A1, string B1, string C1, string A2, string B2, string C2, string A3, string B3, string C3, string A4, string B4, string C4*/)
{
A = returnLine("a.txt", 0);
B = returnLine("a.txt", 1);
C = returnLine("a.txt", 2);
}
public static string returnLine(string fileName, int line)
{
StreamReader SR = new StreamReader(fileName);
List<string> myList = new List<string>();
string linePath;
while ((linePath = SR.ReadLine()) != null)
myList.Add(linePath);
return myList[line];
}
所以,当我这样做时:
Functions.PS3.restoreAllClassesNames(textBox1.Text, textBox2.Text, textBox3.Text);
我的textbox1,2&amp; 3什么都没有,但它应该工作
答案 0 :(得分:6)
您传递的是每个Text
的{{1}}属性的值,因此在TextBox
方法中更改该值对原始控件不起任何作用。
您可以自己传递控件(因为它们是引用类型):
restoreAllClassesNames
或制作字符串public static void restoreAllClassesNames(Control A, Control B, Control C)
{
A.Text = returnLine("a.txt", 0);
B.Text = returnLine("a.txt", 1);
C.Text = returnLine("a.txt", 2);
}
参数:
out
并从调用方法将文本分配给控件:
public static void restoreAllClassesNames(out string A, out string B, out string C)
{
A = returnLine("a.txt", 0);
B = returnLine("a.txt", 1);
C = returnLine("a.txt", 2);
}
您还可以返回string a;
string b;
string c;
Functions.PS3.restoreAllClassesNames(out a, out b, out c);
textBox1.Text = a;
textBox2.Text = b;
textBox3.Text = c;
,List<string>
等等。
答案 1 :(得分:0)
StreamReader正在bin \ Debug \ folder
中查找该文件您可以提供文件路径
public static string returnLine(string fileName, int line)
{
var filepath = "D:/" + fileName; /*Your file path*/
if (File.Exists(filepath))
{
StreamReader SR = new StreamReader(filepath);
List<string> myList = new List<string>();
string linePath;
while ((linePath = SR.ReadLine()) != null)
myList.Add(linePath);
if (myList.Count > 0)
return myList[line];
else
return "No record found";
}
else
{
return "File not found";
}
}
答案 2 :(得分:-1)
传递字符串的引用而不是其值:
public static void restoreAllClassesNames( ref string A, ref string B, ref string C/*, string A1, string B1, string C1, string A2, string B2, string C2, string A3, string B3, string C3, string A4, string B4, string C4*/)
{
A = returnLine("a.txt", 0);
B = returnLine("a.txt", 1);
C = returnLine("a.txt", 2);
}
你可以像这样调用你的方法
string txt1 = textBox1.Text;
string txt2 = textBox2.Text;
string txt3 = textBox3.Text;
Functions.PS3.restoreAllClassesNames(ref txt1 , ref txt2 , ref txt3 );
textBox1.Text = txt1;
textBox2.Text = txt2;
textBox3.Text = txt3;