简体   繁体   English

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

[英]How to declare/set a static variable inside a method

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. 阅读完答案后,我编辑了我的代码,但我仍然无法获得静态变量_user。 What I am doing wrong? 我做错了什么?

    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";

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. 在您的代码中,public static属性完全独立于私有静态字段。

Try this: 尝试这个:

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

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

The property _User creates its own invisible private backing field, which is why it is entirely separate from the private _user field you declared elsewhere. 属性_User创建自己的不可见私有支持字段,这就是它与您在其他地方声明的私有_user字段完全分开的原因。

(Style guidelines dictate the name User for 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; } } 
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM