如何在C#中创建全局变量? [英] How to create a global variable in C#?

查看:85
本文介绍了如何在C#中创建全局变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在.net项目中使用全局变量.但是,我无法在两种方法之间进行处理.

I need to use a global variable in my .net project. However, i cannot handle it between two methods..

我的代码:

string str;
protected void Page_Load(object sender, EventArgs e)
{
    if (!Page.IsPostBack)
    {
        str = "i am a string";
        showString();
    }
}

void showString()
{
    aspLabel.Text = str; //error
}

问题更新:

Question update:

我不会考虑使用 showString(str),因为此变量使用了很多方法.例如,我有一个click事件需要使用它.

I will not consider to use showString(str) because this variable is used many methods.. For example, I have a click event which need to use it.

protected void Btn_Click(object sender, EventArgs e)
{
    exportToExcel(str);
}

因此,我需要在全局范围内创建它!

Therefore, I need to create it in global!

推荐答案

答案是不要做全局变量(您也不能做).

The answer is don't do global variables (you also can't).

最接近 Global 的是将其放在 static 且具有 static 成员的类中-但我真的认为这将是在大多数情况下使用错误的方法. Static 类/成员通常会使代码更加耦合并降低可测试性,因此在您决定这样做时请仔细选择.

Closest to Global is having it in a class that is static and has a static member - but I really think it would be the wrong approach for most of the cases. Static classes/members usually make code more coupled and reduces testability so pick carefully when you decide to do so.

改为:(传递参数)

protected void Page_Load(object sender, EventArgs e)
{
  if (!Page.IsPostBack)
  {
    string str = "i am a string";
    showString(str);
  }
}

void showString(string str)
{
  aspLabel.Text = str;
}

或者:

public class SomeClass
{
    private string str;

    protected void Page_Load(object sender, EventArgs e)
    {
      if (!Page.IsPostBack)
      {
        str = "i am a string";
        showString();
      }
    }

    protected void Btn_Click(object sender, EventArgs e)
    {
       exportToExcel(str);
    }

    void showString()
    {
      aspLabel.Text = str;
    }
}

在这里,您可以根据需要将 str 更改为属性或其他访问修饰符,但这是一般性的想法.

Here you can change the str to be a property or a different access modifier as you wish, but this is the general idea.

如果将其设置为公共而不是私有,则可以从持有该类实例的其他类访问它.像这样:

public class SomeClass
{
    public string Str { get; private set; }

    protected void Page_Load(object sender, EventArgs e)
    {
      if (!Page.IsPostBack)
      {
        Str = "i am a string";
        showString();
      }
    }

    protected void Btn_Click(object sender, EventArgs e)
    {
       exportToExcel(Str);
    }

    void showString()
    {
      aspLabel.Text = Str;
    }
}

public class SomeOtherClass
{
    public SomeOtherClass()
    {
        SomeClass someClass = new SomeClass();
        var otherStr = someClass.Str;
    }
}

这篇关于如何在C#中创建全局变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆