我有一个名为currentUser的类,另一个叫做游戏。从游戏,我试图从currentUser访问一个变量,我知道该变量是创建的,它在currentUser中包含一些东西,然后我在游戏中调用它,但我得到一个空字符串。我在这做错了什么这就是我所拥有的
public class currentUser
{
private string currentUser;
public string getCurrentUser
{
get {return currentUser;}
set {currentUser = value;}
}
//this gets pushed in the beginning of the program
private void btn_click(object sender, RoutedEventArgs e)
{
currentUser = txtUsername.Text;
}
}
public class game
{
currentUser myCurrentUser = new currentUser();
string var = myCurrentUser.getCurrentUser();
//this is another method being called in another class, but i dont think it is relevant. by the time i step over to here, var is null.
clsScores.getScore(25, var);
}
我试过看,但这是我看到的同样的例子,所以我不知道为什么它不起作用。
答案 0 :(得分:1)
试试这个:(我不知道你是如何在游戏中调用代码的,所以我只是用DoSomething方法调用它)。如果您得到“无名称”的结果,则表示从文本框中获取用户存在问题。
public class CurrentUser
{
private string _user;
public string User
{
get { return _user; }
set { _user = value; }
}
//this gets pushed in the beginning of the program
private void btn_click(object sender, RoutedEventArgs e)
{
if(String.IsNullOrEmpty(txtUsername.Text)
{
_user = "No name";
}
else
{
_user= txtUsername.Text;
}
}
}
public class Game
{
public void DoSomething()
{
var myCurrentUser = new CurrentUser();
var user = myCurrentUser.User;
Console.WriteLine(user);
}
}
答案 1 :(得分:0)
您不小心将括号放入:
string var = myCurrentUser.getCurrentUser();
删除它们是因为" getCurrentUser"是一种财产,而不是一种方法。属性不需要括号。
答案 2 :(得分:0)
除非你在“currentUser myCurrentUser = new currentUser();”之间的时间内设置“currentUser”,否则提到很多其他问题。和“string var = myCurrentUser.getCurrentUser();”。你的变量永远不会被设置。