C# 如何在方法中声明/设置静态变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9873635/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 11:01:50  来源:igfitidea点击:

How to declare/set a static variable inside a method

c#methodsstaticgetset

提问by kmxillo

I cannot get/set a static variable inside a method. How can I do it?

我无法在方法中获取/设置静态变量。我该怎么做?

    public class LoginDialog
{
    // class members

    private static string _user=""  ;

    public  void RunDialog()
    {

        _user = "Peter";

    }

    public static string _User { get; set; }

}

After reading the answers I edit my code and I cant still get the static variable _user. What I am doing wrong?

阅读答案后,我编辑了我的代码,但仍然无法获得静态变量 _user。我做错了什么?

    public class LoginDialog
{   
    private static string _user;  

    public void RunDialog()
    {
       LoginDialog._user = "Peter";
    }
    public static string _User { get {return _user;}  }
}

When I declare like that everything works fine, but rather I would like to declare inside the method.

当我声明一切正常时,我想在方法内部声明。

 private static string _user="Peter";

采纳答案by phoog

The problem is that you're setting a private static field, and then presumably reading the public static property elsewhere. In your code, the public static property is completely independent of the private static field.

问题是您正在设置一个私有静态字段,然后大概在其他地方读取公共静态属性。在您的代码中,公共静态属性完全独立于私有静态字段。

Try this:

尝试这个:

public class LoginDialog 
{ 
    // class members
    public  void RunDialog() 
    {
        _User = "Peter";
    }

    public static string _User { get; private set; } 
} 

The property _Usercreates its own invisible private backing field, which is why it is entirely separate from the private _userfield you declared elsewhere.

该属性_User创建了自己不可见的私有支持字段,这就是为什么它与_user您在其他地方声明的私有字段完全分开的原因。

(Style guidelines dictate the name Userfor the public static property, but that's just a guideline.)

(样式指南规定了User公共静态属性的名称,但这只是一个指南。)

Here's another approach, for earlier versions of C# that do not support automatic properties, and without the underscore in the public property name:

这是另一种方法,适用于不支持自动属性且公共属性名称中没有下划线的早期版本的 C#:

public class LoginDialog 
{
    private static string _user;

    // class members
    public  void RunDialog() 
    {
        _user = "Peter";
    }

    public static string User { get { return _user; } } 
}