Definition and use of global scope constants, fields, properties and methods in C

Time:2020-2-26

scene

In development, there are often some global scope constants, fields, properties, methods, etc.

These need to be set to global scope save and have unique instances.

Note:

Blog home page:
https://blog.csdn.net/badao_liumang_qizhi

Official account
Domineering procedural ape
Get programming related ebooks, tutorials and free downloads.

Realization

First, create a global class. The name is optional. This is global.

 public class Global
        {
            
        }

To ensure the singleton implementation, set the following in the class

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

Global constant implementation

public const int INDENT = 5;

Public const string font Ou family = "Tahoma";

Global field implementation

private string _currCompareDataFile;

private List _compareData = new List();

Global attribute implementation

public string CurrCompareDataFile
        {
            get { return _currCompareDataFile; }
            set { _currCompareDataFile = value; }
        }
public List CompareData
        {
            get {
                return _compareData; 
                }
            set { _compareData = value; }
        }

 

Note:

The global field is used in combination with the property. The above is declared, and the settings of get and set are set below.

If there are special settings in value or assignment, you can also

public string CurrChartTitle
        {
            get
            {
                if (String.IsNullOrEmpty(this._currDataFile))
                {
                    Return "default title";
                }
                else
                {
                    return System.IO.Path.GetFileNameWithoutExtension(String.Format("{0}{1}", this._currDataFile, Global.MAIN_EXT));
                }
            }
        }

 

Global method implementation

 public void Init()
        {
            
        }

Use examples

Constant usage

Global. Constant name

Global.XAXIS_ATTRIBUTE_XPATH

Field usage

Fields are generally used in combination with attributes in global

public string CurrCompareDataFile
        {
            get { return _currCompareDataFile; }
            set { _currCompareDataFile = value; }
        }

Attribute usage

Global.Instance.CurrCompareDataFile

Use of methods

Global.Instance.Init();