当前位置: 移动技术网 > IT编程>开发语言>c# > C#中全局作用域的常量、字段、属性、方法的定义与使用

C#中全局作用域的常量、字段、属性、方法的定义与使用

2019年10月15日  | 移动技术网IT编程  | 我要评论
场景 在开发中,经常会有一些全局作用域的常量、字段、属性、方法等。 需要将这些设置为全局作用域保存且其实例唯一。 注: 博客主页: https://blog.csdn.net/badao_liumang_qizhi 关注公众号 霸道的程序猿 获取编程相关电子书、教程推送与免费下载。 实现 首先新建一 ...

场景

在开发中,经常会有一些全局作用域的常量、字段、属性、方法等。

需要将这些设置为全局作用域保存且其实例唯一。

注:

博客主页:

关注公众号
霸道的程序猿
获取编程相关电子书、教程推送与免费下载。

实现

首先新建一个全局的class,名字随意,这里叫global。

 public class global
        {
            
        }

为了保证其单例实现,在类中设置如下

 private static string _lockflag = "globallock";
        private static global _instance;
        private global()
        {

        }

        public static global instance
        {
            get
            {
                lock (_lockflag)
                {
                    if (_instance == null)
                    {
                        _instance = new global();
                    }
                    return _instance;
                }
            }
        }

全局常量实现

public const int indent = 5;

public const string font_family = "宋体";

全局字段实现

private string _currcomparedatafile;

private list<datatreenode> _comparedata = new list<datatreenode>();

全局属性实现

public string currcomparedatafile
        {
            get { return _currcomparedatafile; }
            set { _currcomparedatafile = value; }
        }
 public list<datatreenode> comparedata
        {
            get {
                return _comparedata; 
                }
            set { _comparedata = value; }
        }

 

注:

全局字段与属性对应配合使用,上面进行声明,下面进行get和set的设置。

如果在取值或者赋值时有特殊的设置,还可以

public string currcharttitle
        {
            get
            {
                if (string.isnullorempty(this._currdatafile))
                {
                    return "默认标题";
                }
                else
                {
                    return system.io.path.getfilenamewithoutextension(string.format("{0}{1}", this._currdatafile, global.main_ext));
                }
            }
        }

 

全局方法实现

 public void init()
        {
            
        }

使用举例

常量使用

global.常量名

global.xaxis_attribute_xpath

字段使用

字段一般是在global里配合属性使用

public string currcomparedatafile
        {
            get { return _currcomparedatafile; }
            set { _currcomparedatafile = value; }
        }

属性使用

global.instance.currcomparedatafile

方法的使用

global.instance.init();

 

如您对本文有疑问或者有任何想说的,请 点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网