2015-06-01 18 views
1

我需要使用下面的程序类的字符串变量到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; 
     } 
    } 
+2

请进一步明确的问题,并发布TelnetInterface(类?)。 –

+0

您需要实例化一个类型为“TelnetConnection”的对象,或者使方法“Login”静态以便能够在“Program.main()” –

回答

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

中使用它,谢谢。 – Member123