C# 有没有更好的方法来初始化 .NET 中的 Hastable 而不使用 Add 方法?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/128343/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-03 14:48:05  来源:igfitidea点击:

Is there a better way to initialize a Hastable in .NET without using Add method?

提问by hectorsq

I am currently initializing a Hashtable in the following way:

我目前正在通过以下方式初始化 Hashtable:

Hashtable filter = new Hashtable();
filter.Add("building", "A-51");
filter.Add("apartment", "210");

I am looking for a nicer way to do this.

我正在寻找一种更好的方法来做到这一点。

I tried something like

我试过类似的东西

Hashtable filter2 = new Hashtable() {
    {"building", "A-51"},
    {"apartment", "210"}
};

However the above code does not compile.

但是上面的代码不能编译。

采纳答案by Paul Batum

The exact code you posted:

您发布的确切代码:

        Hashtable filter2 = new Hashtable()
        {
            {"building", "A-51"},
            {"apartment", "210"}
        };

Compiles perfectly in C# 3. Given you reported compilation problems, I'm guessing you are using C# 2? In this case you can at least do this:

在 C# 3 中完美编译。鉴于您报告了编译问题,我猜您正在使用 C# 2?在这种情况下,您至少可以这样做:

        Hashtable filter2 = new Hashtable();
        filter2["building"] = "A-51";
        filter2["apartment"] = "210";

回答by mattlant

In C# 3 it should compile fine like this:

在 C# 3 中,它应该可以像这样编译:

Hashtable table = new Hashtable {{1, 1}, {2, 2}};

回答by JeeBee

(Not a C# expert)

(不是 C# 专家)

This is syntactic sugar, and if it's syntactic sugar I'd want to have the mapping (in a Hashtable) nice and obvious:

这是语法糖,如果它是语法糖,我希望映射(在 Hashtable 中)漂亮而明显:

Hashtable filter2 = new Hashtable() { "building" => "A-51", "apartment" => "210"};

However I don't see a real need for this, there isn't much wrong with just having to call add after initialisation.

但是,我认为没有真正的需要,在初始化后调用 add 并没有太大问题。

(I've known people to hack around with the Java compiler to achieve similar things in the past for Java (which caused major issues moving to Java 5 a few years later), I expect this isn't an option for C# though!)

(我知道人们在过去使用 Java 编译器来为 Java 实现类似的事情(这导致了几年后转移到 Java 5 的重大问题),但我希望这不是 C# 的选项!)

回答by SeaDrive

I think the real question being asked may be about imaginable constructors such as:

我认为被问到的真正问题可能是关于可想象的构造函数,例如:

HashTable ht = new HashTable(MyArray) ; // fill from array

HashTable ht = new HashTable(MyArray) ; // 从数组中填充

HashTable ht = new HashTable(MyDataTable) ; // fill from datatable

HashTable ht = new HashTable(MyDataTable) ; // 从数据表中填充

AFAIK, the answer is "no", but you could write it yourself. I assume the reason that such methods are not in the library is that the Array or DataTable has to be properly formed. It's not such a big loss since any implementation of these methods would probably be using the Add method in a loop anyway.

AFAIK,答案是“不”,但您可以自己编写。我认为此类方法不在库中的原因是必须正确形成 Array 或 DataTable。这并不是一个很大的损失,因为这些方法的任何实现都可能会在循环中使用 Add 方法。

回答by Ta01

I had no idea in C# 3.0 Hashtable table = new Hashtable {{1, 1}, {2, 2}};would compile.

我不知道在 C# 3.0 中Hashtable table = new Hashtable {{1, 1}, {2, 2}};会编译。

Anyway, poor man's implementation:

无论如何,穷人的实现:

Meh, you could extend the Hashtable class:

嗯,你可以扩展 Hashtable 类:

class MyHashTable : System.Collections.Hashtable    
{
    public MyHashTable(string [,] values)
    {
        for (int i = 0; i < (values.Length)/2; i++)
        {
            this.Add(values[i,0], values[i,1]);
        }
    }
}

And then from a Console App:

然后从控制台应用程序:

    class Program
{
    static void Main(string[] args)
    {
        string[,] initialize = { { "building", "A-51" }, { "apartment", "210" }, {"wow", "nerf Druids"}};



        MyHashTable myhashTable = new MyHashTable(initialize);
        Console.WriteLine(myhashTable["building"].ToString());
        Console.WriteLine(myhashTable["apartment"].ToString());
        Console.WriteLine(myhashTable["wow"].ToString());
        Console.ReadKey();


    }
}

will result in:
A-51
210
nerf Druids

将导致:
A-51
210
nerf Druids

this was done quick so it may bomb in certain situations but then again..

这是快速完成的,因此它可能会在某些情况下爆炸,但又一次..