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

时间:2015-06-01 09:02:54

标签: c# telnet

我需要使用以下字符串变量的程序类来实现TelnetConnection类,我尽一切可能但是没有用,请给我一些sugessions。 谢谢。

计划类

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

TelnetConnection类

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

1 个答案:

答案 0 :(得分:4)

它应该是这样的:

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