What does this expression a[b] represent in C#
I have often seen this expression in a maintenance code
Global["Name"]
What does this represent? I ha开发者_运维知识库ve used Global.Name
but never Global["Name"]
?
Is there are a place where this type of expression is used?
This is called an indexer. In that case, Global
is probably some kind of dictionary or hashtable. "Name"
is a key to access a particular item in that dictionary
It's used when looking up dictionaries and collections containing key/value pairs, eg.
var peopleAges = new System.Collections.Generic.Dictionary<string, int>();
peopleAges["fred"] = 21;
peopleAges["emma"] = 18;
var fredAge = peopleAges["fred"]; // returns 21
It is a form of short hand allowed by C# called a default property. When an class has DefaultMemberAttribute set C# allows the name of the property named in that attribute to be omitted in that way.
精彩评论