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

后端 未结 2 1515
梦如初夏
梦如初夏 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:13

    You are not using the same instance. Try

    public class MyClass
    {
        private string _user;
        public string user
        { get { return this._user; } set { this._user = value; } }
    
    }
    
    public string YourFunction()
    {
       MyClass m = new MyClass();
       m.user = "abc"
       return m.user;
    
    }
    

    If all you want to return is a string try something like

    string x = YourFunction();
    
    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题