How to acess variable value from one class to another class?

后端 未结 2 1517
梦如初夏
梦如初夏 2021-02-06 12:59

I want to access a string from one class to another. I have used the property method as follows -

Myclass.cs

public class MyClass
{
    private string _user;
           


        
2条回答
  •  再見小時候
    2021-02-06 13:29

    As already mentioned in the comments you are creating two separate instances of MyClass which results simplified in something like:

    int a;
    a = 3;
    int b;
    Console.WriteLine("a: " + b); //<-- here it should be obvious why b is not 3
    

    You can work around this in 3 ways:

    1) Use the same instance of MyClass for the second call, but in this case you need to be in the same scope or pass the instance on to the new scope.

    2) Make the property/member static:

    public class MyClass
    {
        public static string User { get; set; } //the "static" is the important keyword, I just used the alternative property declaration to keep it shorter
    }
    

    Then you can access the same User value everywhere via MyClass.User.

    3) Use a singleton:

    public class MyClass
    {
        private static MyClass instance = null;
        public static MyClass Instance 
        {
            get
            {
                if(instance == null)
                    instance = new MyClass();
                return instance;
            }
        }
    
        public string User { get; set; }
    }
    

    Then you can access it via MyClass.Instance.User.

    There are possibly some more solutions, but these are the common ones.

提交回复
热议问题