Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
388 views
in Technique[技术] by (71.8m points)

c# - Initialize dictionary at declaration using PowerShell

Given this powershell code:

$drivers = New-Object 'System.Collections.Generic.Dictionary[String,String]'
$drivers.Add("nitrous","vx")
$drivers.Add("directx","vd")
$drivers.Add("openGL","vo")

Is it possible to initialize this dictionary directly without having to call the Add method. Like .NET allows you to do?

Something like this?

$foo = New-Object 'System.Collections.Generic.Dictionary[String,String]'{{"a","Alley"},{"b" "bat"}}

[not sure what type of syntax this would involve]

question from:https://stackoverflow.com/questions/6765375/initialize-dictionary-at-declaration-using-powershell

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

No. The initialization syntax for Dictionary<TKey,TValue> is C# syntax candy. Powershell has its own initializer syntax support for System.Collections.HashTable (@{}):

$drivers = @{"nitrous"="vx"; "directx"="vd"; "openGL"="vo"};

For [probably] nearly all cases it will work just as well as Dictionary<TKey,TValue>. If you really need Dictionary<TKey,TValue> for some reason, you could make a function that takes a HashTable and iterates through the keys and values to add them to a new Dictionary<TKey,TValue>.


The C# initializer syntax isn't exactly "direct" anyway. The compiler generates calls to Add() from it.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...