如何在实例化时将值插入到 VB.NET 字典中?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1664514/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to insert values into VB.NET Dictionary on instantiation?
提问by onsaito
Is there a way that I can insert values into a VB.NET Dictionary when I create it? I can, but don't want to, do dict.Add(int, "string") for each item.
有没有办法在创建 VB.NET 字典时将值插入它?我可以,但不想,为每个项目做 dict.Add(int, "string") 。
Basically, I want to do "How to insert values into C# Dictionary on instantiation?"with VB.NET.
基本上,我想做“如何在实例化时将值插入 C# 字典?” 与 VB.NET。
var dictionary = new Dictionary<int, string>
{
{0, "string"},
{1, "string2"},
{2, "string3"}
};
回答by brendan
If using Visual Studio 2010 or later you should use the FROM
keyword like this:
如果使用 Visual Studio 2010 或更高版本,则应使用如下FROM
关键字:
Dim days = New Dictionary(Of Integer, String) From {{0, "string"}, {1, "string2"}}
See: http://msdn.microsoft.com/en-us/library/dd293617(VS.100).aspx
请参阅:http: //msdn.microsoft.com/en-us/library/dd293617(VS.100).aspx
If you need to use a prior version of Visual Studio and you need to do this frequently you could just inherit from the Dictionary class and implement it yourself.
如果您需要使用以前版本的 Visual Studio 并且需要经常执行此操作,您可以从 Dictionary 类继承并自己实现它。
It might look something like this:
它可能看起来像这样:
Public Class InitializableDictionary
Inherits Dictionary(Of Int32, String)
Public Sub New(ByVal args() As KeyValuePair(Of Int32, String))
MyBase.New()
For Each kvp As KeyValuePair(Of Int32, String) In args
Me.Add(kvp.Key, kvp.Value)
Next
End Sub
End Class
回答by Stefan
This is not possible versions of Visual Basic prior to 2010.
这不是 2010 年之前的 Visual Basic 版本。
In VB2010 and later, you can use the FROM
keyword.
在 VB2010 及更高版本中,您可以使用FROM
关键字。
Dim days = New Dictionary(Of Integer, String) From {{0, "Sunday"}, {1, "Monday"}}
Reference
参考
http://msdn.microsoft.com/en-us/library/dd293617(VS.100).aspx
http://msdn.microsoft.com/en-us/library/dd293617(VS.100).aspx
回答by Joel Coehoorn
What you're looking at is a feature of C# called "collection initializers". The feature existed for VB as well, but was cut prior to the release of Visual Studio 2008. It doesn't help you right now, but this is expected to be available in Visual Studio 2010. In the meantime, you'll have to do it the old fashioned way — call the .Add()
method of your new instance.
您正在查看的是 C# 的一项称为“集合初始值设定项”的功能。该功能也存在于 VB 中,但在 Visual Studio 2008 发布之前被删除。它现在对您没有帮助,但预计在 Visual Studio 2010 中可用。与此同时,您必须用老式的方式来做——调用.Add()
你的新实例的方法。