繁体   English   中英

C#从另一个类设置并从另一个类获取

[英]C# Set from another class and Get from another class

这是A级

Class A
{    
public string uname { get; set; }
public string fname { get; set; }
}

我按B类设置值

Class B
{
private void Main(){

A aGetSet = new A();   

aGetSet.uname = "James";    
aGetSet.fname = "Blunt"; 
}

}

但是当我在C类中获得值时,它总是返回null

Class C
{
   private void Main()   {

   A aGetSet = new A(); 

   string username = aGetSet.uname;
   string fistname = aGetSet.fname;
}
}

有谁能解决这个问题?

B声明的aGetSetA的对象。 C声明的aGetSetA另一个对象。 它们彼此完全独立。 更改一个对象的值不会影响另一个对象的值。

要解决此问题,您需要使其能够访问BC的同一实例。

有很多方法可以做到这一点。 我将向您展示如何使用单例模式。

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

}

现在,您只需致电C.Main即可完成这项工作!

您有2个类别的2个不同的对象。 当您使用'= new A()'时,它将创建新实例。

您在此处变为空的原因:

string username = aGetSet.uname;

是字符串类型的默认值(与任何引用类型一样)为null。

将类B中的“相同”对象传递给类C的主要方法将类C中的方法更改为公共Main(ref A obj)。 那将不会创建副本并使用相同的实例。 B类致电:

A aObj = new A();
aGetSet.uname = "James"; 
aGetSet.fname = "Blunt"; 
C c = new C();
c.Main(ref aObj);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM