简体   繁体   中英

C# Set from another class and Get from another class

This's Class A

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

I set values by Class B

Class B
{
private void Main(){

A aGetSet = new A();   

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

}

But when I get values in Class C, it's always return null

Class C
{
   private void Main()   {

   A aGetSet = new A(); 

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

Does anyone has solution for this problem?

The aGetSet declared in B is an object of A . The aGetSet declared in C is another object of A . They are completely independent of each other. Changing the values of one of the objects does not affect the values of the other.

To fix this problem, you need to make it so that you are accessing the same instance in B and C .

There are lots of ways to do this. I will show you how to use the singleton pattern.

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

}

Now you just need to call C.Main to make this work!

Your have 2 different objects in 2 classes. When you are using '= new A() ' it creates new instance.

The reason why you are getting null here:

string username = aGetSet.uname;

is default value for string type (as any reference type) is null.

To pass 'the same' object from class B into class C Main method change method in class C to public Main(ref A obj). That will not create a copy and use the same instance. Call from class B:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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