这是A级
Class A
{
public string uname { get; set; }
public string fname { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
我按 B 类设置值
Class B
{
private void Main(){
A aGetSet = new A();
aGetSet.uname = "James";
aGetSet.fname = "Blunt";
}
}
Run Code Online (Sandbox Code Playgroud)
但是当我在 C 类中获取值时,它总是返回 null
Class C
{
private void Main() {
A aGetSet = new A();
string username = aGetSet.uname;
string fistname = aGetSet.fname;
}
}
Run Code Online (Sandbox Code Playgroud)
有没有人有解决这个问题的方法?
该aGetSet宣布B是一个对象A。该aGetSet宣布C是另一个对象A。它们彼此完全独立。更改一个对象的值不会影响另一个对象的值。
为了解决这个问题,你需要它,以便您正在访问的同一实例B和C。
有很多方法可以做到这一点。我将向您展示如何使用单例模式。
class A
{
public string uname { get; set; }
public string fname { get; set; }
private A() {} // mark this private so that no other instances of A can be created
public static readonly A Instance = new A();
}
class B
{
public void Main(){
// here we are setting A.Instance, which is the only instance there is
A.Instance.uname = "James";
A.Instance.fname = "Blunt";
}
}
class C
{
public void Main() {
B b = new B();
b.Main();
string username = A.Instance.uname;
string fistname = A.Instance.fname;
}
}
Run Code Online (Sandbox Code Playgroud)
现在你只需要打电话C.Main来完成这项工作!