I want to refer to a variable in one class in another.

Asked 2 years ago, Updated 2 years ago, 37 views

Hello, I'm a beginner in C#. I've been using C only I'm working on the basics of c# For example,


public class A
{
    public string a;
    public int b;
}

public class B
{
    var tmp = new A();
    tmp.a = null;
    tmp.b = 0;
}
public class C
{
   //The part where you want to recall the changed value in B!
}

The variables declared in class A are initialized in class B as shown above Next, I'd like to call the changed value from B in class C If you use static, you will break the attribute rule of encapsulation, so you don't want to use it as much as possible Please give me your opinion on which method to use. ㅜㅜ<

c#

2022-09-21 15:16

2 Answers

We recommend that you use Singleton Pattern if you want to put data in an instance of a particular class and change it from time to time in multiple classes.

There are various ways to implement Singleton Pattern in C#, so please refer to the link below.

http://csharpindepth.com/articles/general/singleton.aspx


2022-09-21 15:16

First, the easiest way is to use static.

But it's not a good way.

The recommended method is Registry Pattern.

http://wiki.c2.com/?RegistryPattern

You create an object in a single-turn pattern and manage variables using maps or lists from that object. This allows you to manage global variables because the object is unique.

This method is unique to jvm, so a clustered structure might require a device to synchronize.

If you don't know what the Singleton pattern is...Try learning Object generation pattern and simple structure. Of course, this also uses static.


2022-09-21 15:16

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.