开发者

What does this expression a[b] represent in C#

开发者 https://www.devze.com 2023-01-13 07:46 出处:网络
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\"]?

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号