c#静态变量和静态属性的区别

编程初段通常比较喜欢使用静态变量,和静态方法,因为很方便,不用仔细构建框架。但是对封装性破坏很大,internal static 或public static 声明的东西几乎程序里什么地方都可以使用,但是我觉得很容易出问题。 前几天碰到一个问题, 程序启动的时候需要检查一下配置目录,当不存在此目录,就去创建一个。

程序如下:

    public class ClassDebug
    {
        public static string 静态属性
          {
            get
            {
                string tempPath =
                    Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory), "配置目录");
                if (!Directory.Exists(tempPath))
                {
                    Directory.CreateDirectory(tempPath);
                }
                return tempPath;
            }
        }
    }
public class HostInfo
    {
        private string _ip = "127.0.0.1";
        private string _port = "80";

        public string Ip
        {
            get { return _ip; }
            set { _ip = value; }
        }

        public string Port
        {
            get { return _port; }
            set { _port = value; }
        }
    }

下面程序一运行,就把目录创建出来,没有机会在初始化阶段对目录做任何修改。拿到的是默认的Ip和Port的值。

public static string MyPath= Path.Combine(ClassDebug.ClassDebug.静态属性, host.Ip + "_" + host.Port);
      
        public static void Main(string[] args)
        {
            //其他代码
            Console.ReadLine();
        }
    

下面才是正确的做法,有时候真是不能只图省事,写少几行代码。但是静态变量我总觉得没什么好处。

        public static string MyPath
        {
            get
            {
                //给机会外部修改目录的机会
                    HostInfo host = new HostInfo();
                host.Ip = LoginWindow.Ip;
                host.Ip = LoginWindow.Port;
                return Path.Combine(ClassDebug.ClassDebug.静态属性, host.Ip + "_" + host.Port);
            }
        }
public static void Main(string[] args)
        {
            //其他代码
            Console.ReadLine();
        }
原文地址:https://www.cnblogs.com/grkin/p/3084897.html