如何将程序 class 的变量用于另一个 class?

How to use variable of program class to another class?

我需要使用程序 class 的以下字符串变量到 TelnetConnection class,我尝试了所有可能的方法,但都没有奏效,请给我建议。 谢谢。

程序class

 class Program
 {      
    static void main()
    {
     string s = telnet.Login("some credentials");
    }
 }

TelnetConnectionclass

 class TelnetConnection
 {
      public string Login(string Username, string Password, int LoginTimeOutMs)
        {

            int oldTimeOutMs = TimeOutMs;
            TimeOutMs = LoginTimeOutMs;

            WriteLine(Username);

            s += Read();

            WriteLine(Password);

            s += Read();
            TimeOutMs = oldTimeOutMs;
            return s;
        }
  }

应该是这样的:

public class TelnetConnection
{
  public string Login(string Username, string Password, int LoginTimeOutMs)
  {
        string retVal = "";

        int oldTimeOutMs = TimeOutMs;
        TimeOutMs = LoginTimeOutMs;

        WriteLine(Username);

        retVal += Read();

        WriteLine(Password);

        retVal  += Read();
        TimeOutMs = oldTimeOutMs;
        return retVal ;
    }
 }

在计划中:

class Program
{      
    static void main()
    {
         var telnet = new TelnetConnection();
         string s = telnet.Login("some username", "some password", 123);
    }
 }

但是您的示例中似乎缺少一些代码,尤其是 Read 方法的实现。

如果你想改变程序的字符串变量,你可以用ref关键字将它传递给方法:

public class TelnetConnection
{
  public string Login(string Username, 
                      string Password, int LoginTimeOutMs, ref string retVal)
  {
        //omitted
        retVal += Read();

        WriteLine(Password);

        retVal  += Read();
        TimeOutMs = oldTimeOutMs;
        return retVal ;
    }
 }

在计划中:

class Program
{      
    static void main()
    {
         var telnet = new TelnetConnection();
         string s = ""; 
         telnet.Login("some username", "some password", 123, ref s);
         //s is altered here
    }
 }