更新: 请注意关闭这个,我在分配授权的错误,我没有将它分配给实例。
我遇到以下代码的问题,基本上我有两个单独的类,它们在我的" MainWindow"的顶部声明:
public partial class MainWindow : MetroWindow
{
public Auth AuthInfo = Auth.GetInstance();
public api myApi = api.GetInstance();
在MainWindow类中进一步设置它的行,如果我在赋值后调试它,则设置了Authorization字符串。
AuthInfo = JsonConvert.DeserializeObject<Auth>(responseString);
类声明如下:
验证
public class Auth
{
private static Auth instance = new Auth();
private Auth(){}
public static Auth GetInstance()
{
return instance;
}
public string Authorisation { get; set; }
}
API
public class api
{
private static api instance = new api();
Auth AuthInfo = Auth.GetInstance();
private api(){}
public static api GetInstance()
{
return instance;
}
// other code goes here
}
问题是当我尝试从api类中访问Auth实例的Authorization属性时,它没有设置?它几乎像GetInstance返回没有任何属性的实例?
在MainWindow类中,授权属性是正确的
答案 0 :(得分:1)
试试这个:
public class Auth
{
private static Auth instance = new Auth();
private Auth(){}
public static Auth GetInstance()
{
if (instance == null) \\ADDED
instance = new Auth();
return instance;
}
public string Authorisation { get; set; }
}
答案 1 :(得分:1)
在静态方法本身中实例化:
public class Auth
{
private static Auth instance;
private Auth(){}
public static Auth GetInstance()
{
if (instance == null)
instance = new Auth();
return instance;
}
public string Authorisation { get; set; }
}