c#错误基本函数

本文关键字:函数 错误 | 更新日期: 2023-09-27 18:19:05

我的函数有问题

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

My textbox1, 2 &

c#错误基本函数

您正在传递每个TextBoxText属性的值,因此在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>, Tuple<string, string, string>,等等。

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

传递字符串的引用而不是其值:

  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;

查看此链接