问题描述
我正在开发一个 wpf 应用程序.在这个应用程序中,我收到了来自服务器的 JSON 响应并将其反序列化如下:-
I am working on a wpf application. In this application I received JSON response from server and deserialize it as follow :-
StreamReader streamReader = new StreamReader(jsonResponse.GetResponseStream());
String responseData = streamReader.ReadToEnd();
var myData = JsonConvert.DeserializeObject<List<RootObject>>(responseData);
//UserData ud = new UserData();
foreach (var val in myData)
{
string res = val.response;
if (res == "true")
{
this.Hide();
new lobby().Show();
}
}
我的课程如下:-
public class RootObject
{
public string response { get; set; }
public string user_id { get; set; }
public string username { get; set; }
public string current_balance { get; set; }
public string message { get; set; }
public string oauth_token { get; set; }
public List<string> lastFiveSpinNumbers { get; set; }
}
当我执行此代码时一切正常,并且在检查响应 lobby.xaml
打开后.现在我需要访问 lobby.xaml.cs
中 RootObject
类的值.所以我创建了这个类的一个实例如下:-
When I execute this code everything is ok and after checking response lobby.xaml
open. Now I need to access values of RootObject
class in lobby.xaml.cs
. So I created an instance of this class as follow:-
RootObject cd = new RootObject();
UserNameTextBlock.Text = cd.response;
但 cd.response
始终为空.可能是什么原因?
but cd.response
is always null. What may be the reason?
推荐答案
您正在创建 RootObject
的新实例,默认情况下 response
属性为 null代码>.
You are creating a new instance of RootObject
and by default the response
property is null
.
你可以给你的 lobby
类一个构造函数,它接受一个 RootObject
:
You can give your lobby
class a constructor that takes in a RootObject
:
public class lobby
{
public lobby(RootObject rootObject)
{
UserNameTextBlock.Text = rootObject.response;
}
}
然后在您的 foreach
中,您可以执行以下操作:
Then in your foreach
you could do:
if (res == "true")
{
this.Hide();
new lobby(val).Show(); // Pass the root object to the Lobby constructor
}
注意:您可能希望将 lobby
重命名为 Lobby
作为您的类名,这符合更好的 C#
命名约定.
Note: You may wish to rename lobby
to Lobby
for your class name, this adheres to better C#
naming conventions.
这篇关于从wpf中的另一个类访问公共类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!