Access variable from another method in another class

前端 未结 7 1373
闹比i
闹比i 2020-12-12 06:27

Suppose I have a file ABC.CS in that file I have a class ABC as below and method Test():

public class ABC
{
   public          


        
7条回答
  •  不思量自难忘°
    2020-12-12 07:05

    Using static variables/functions is one thing; accessing a variable from outside of its scope is another thing.

    From MSDN:

    If a local variable is declared with the Static keyword, its lifetime is longer than the execution time of the procedure in which it is declared. If the procedure is inside a module, the static variable survives as long as your application continues running.

    And also static variable will exist per class, not instance.

    So, I assume that you will need instances of ABC class:

    public class ABC
    { 
        private int a; //also you can add 'readonly' if you will not change this value in       its lifetime
        private int b;
        private int c;
    
        public int A()
        {
            get { return a; }
        }
    
        public int B()
        {
            get { return b; }
        }
    
        public int C()
        {
            get { return c; }
        }
    
        public void Test()
        {     
            a=10;
            b=11;
            c=12;
            //many many variables
        }
    }
    

    From another class you can call:

    ABC abcInstance = new ABC();
    abcInstance.Test(); //you set the values
    int aTemp = abcInstance.A(); // now you have the 'a' value of ABC's property.
    

提交回复
热议问题