开发者

How to init a `HashTable` object which use named parameters?

开发者 https://www.devze.com 2023-02-06 04:15 出处:网络
We can init a HashTable object using the below syntax. var listTinhThanh = new System.Collections.Hashtable()

We can init a HashTable object using the below syntax.

var listTinhThanh = new System.Collections.Hashtable()
{ 
    { "key", someObject }
};

I want to use the code in such a manner of:

var listTinhThanh = new System.Collections.Hashtable()
{ 
    { Key:"key", Value:someObject }
};

But that DOES开发者_运维问答N'T work. Do you have any work-around?


No, there isn't a workaround. Such syntax cannot possibly exist in C# because of the :. Also the first seems shorter to me, I wonder why you need the second.

This being said I would recommend you using a strongly typed Dictionary<TKey, TValue> instead of a Hashtable. The closest you could get is this:

var listTinhThanh = new[]
{ 
    new { Key = "key1", Value = someObject1 },
    new { Key = "key2", Value = someObject2 },
    new { Key = "key3", Value = someObject3 },
}.ToDictionary(x => x.Key, x => x.Value);
0

精彩评论

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