How to declare a variable that can be used by every method? | C#

巧了我就是萌 提交于 2021-02-16 18:33:06

问题


I want to ask you how to declare a variable that can be used by every method?

I tried making the method's access type public but that didn't let me used its variable across other methods

Moreover, I basically want to accumulate that variable with different values across different methods that's why I am asking this.

NOTE: I want to avoid making any static classes.

EDIT:

For example, I did

public decimal MiscMethod()  
{
    decimal value1 += 23m;  
}  

public decimal AutoMethod()  
{
    decimal value 1 += 34;
}

回答1:


do you mean somethinge like this ?

class Program
{
    static void Main(string[] args)
    {
        var myClass = new MyClass();
        myClass.Print(); //Output: Hello
        myClass.SetVariable();
        myClass.Print(); //Output: Test

    }
}

class MyClass
{
    string MyGlobaleVariable = "Hello"; //my global variable


    public void SetVariable()
    {
        MyGlobaleVariable = "Test";
    }

    public void Print()
    {
        Console.WriteLine(MyGlobaleVariable);
    }
}

with your example:

decimal value1 = 0;

public decimal MiscMethod()  
{
    value1 += 23m;  
}  

public decimal AutoMethod()  
{
    value1 += 34;
}



回答2:


Use it like a global variable,but make sure after using it in every method you need to nullify the value,as that will not make the value contradictory to other methods.

decimal value1;

public decimal MiscMethod()  
{
    value1 += 23m; 
    //Complete your code using value1
    value1 = 0;
}  

public decimal AutoMethod()
{
    value 1 += 34;
    //Complete your code using value1
    value1 = 0;
}


来源:https://stackoverflow.com/questions/38260309/how-to-declare-a-variable-that-can-be-used-by-every-method-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!