• 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();
            }
  • 相关阅读:
    ASP.NET把客户机IP转换成真实地址(利用纯真 IP 数据库)
    关于分层走班教学的思考
    asp.net jQuery Ajax用户登录功能的实现
    C#判断网络地址 Url 是否存在的方法
    Asp.net获得远程网页源代码
    jQuery Ajax 调用aspx后台方法返回DataTable 的例子
    ASP.NET2.0中将GridView导出为Excel
    利用DataGrid显示某目录下的所有文件
    C#使用存储过程详细
    javascript获取当前日期时间
  • 原文地址:https://www.cnblogs.com/grkin/p/3084897.html
Copyright © 2020-2023  润新知