gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 21:21:14 27 4
gpt4 key购买 nike

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

程序类

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

最佳答案

应该是这样的:

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

关于c# - 如何将程序类的变量用于另一个类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30569513/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com