简体   繁体   中英

Get set on a property for a dictionary?

Simple get set on a property code:

 private int time;
 public int Time
 {
     get
     {
         return time;
     }
     set
     {
         time= value;
     }
}

How can I do it for a dictionary? Or is it not possible?

 private Dictionary<string, float> times = new Dictionary<string, float>();

A comon convention is to use a private field:

private Dictionary<string, float> _times;
public Dictionary<string, float> times
{
    get
    {
        if (_times == null)
        {
            // Initilize the dictionary
            _times = new Dictionary<string, float>();
            _times.Add("bla", 45F);
            //... it will happen one time because _times will be null only one time
            // to make the code more orginized you can call some method tha will initilize the dictionary
            // for example InitTimes(); 
        }

        return _times;
    }
    set
    {
        // The private _times field will be set and when you call times the get method will return _times
        _times = value;
    }
}

First Create the Dictionary like i have create with Value you can create Blank as-

private static Dictionary<string, bool> PressedShortKey = new Dictionary<string, bool> { { "C", false }, { "V", false }, {"X",false }, { "S",false},

         { "P",false}, { "Z",false}, { "Y",false}, { "B",false}

};

and can get or set the value of Dictionary like - PressedShortKey["C"] = true;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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