C# 如何在构造函数中初始化 IDictionary?

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

How to initialize IDictionary in constructor?

c#asp.net-mvc

提问by eKek0

In TagBuilder and other classes I can write something like:

在 TagBuilder 和其他类中,我可以编写如下内容:

var tr = new TagBuilder("HeaderStyle"){InnerHtml = html, [IDictionary Attributes]}

but I don't know how to pass the IDictionary parameter.

但我不知道如何传递 IDictionary 参数。

How can I do that on the fly? Without creating a Dictionary variable.

我怎么能即时做到这一点?无需创建 Dictionary 变量。

TagBuilder is an example, there are other classes that accept a parameter IDictionaryas well. The question is about the generic case.

TagBuilder 就是一个例子,还有其他类也接受参数IDictionary。问题是关于一般情况。

采纳答案by Robert Harvey

The following blog post has a helper method that can create Dictionary objects from anonymous types.

以下博客文章有一个辅助方法,可以从匿名类型创建 Dictionary 对象。

http://weblogs.asp.net/rosherove/archive/2008/03/11/turn-anonymous-types-into-idictionary-of-values.aspx

http://weblogs.asp.net/rosherove/archive/2008/03/11/turn-anonymous-types-into-idictionary-of-values.aspx

void CreateADictionaryFromAnonymousType() 
   { 
       var dictionary = MakeDictionary(new {Name="Roy",Country="Israel"}); 
       Console.WriteLine(dictionary["Name"]); 
   }

private IDictionary MakeDictionary(object withProperties) 
   { 
       IDictionary dic = new Dictionary<string, object>(); 
       var properties = 
           System.ComponentModel.TypeDescriptor.GetProperties(withProperties); 
       foreach (PropertyDescriptor property in properties) 
       { 
           dic.Add(property.Name,property.GetValue(withProperties)); 
       } 
       return dic; 
   }

回答by John Saunders

If you're referring to the Attributes property, the setter is private, so you can't set it in an object initializer.

如果您指的是 Attributes 属性,则 setter 是私有的,因此您不能在对象初始值设定项中设置它。

After you've initialized the TagBuilder, you should be able to add individual attributes with tr.Attributes.Add(key,value).

初始化 TagBuilder 后,您应该能够使用tr.Attributes.Add(key,value).

回答by Robert Harvey

Another way to create Dictionaries from Anonymous types:

从匿名类型创建字典的另一种方法:

new Dictionary<int, StudentName>()
{
    { 111, new StudentName {FirstName="Sachin", LastName="Karnik", ID=211}},
    { 112, new StudentName {FirstName="Dina", LastName="Salimzianova", ID=317}},
    { 113, new StudentName {FirstName="Andy", LastName="Ruth", ID=198}}
};

http://msdn.microsoft.com/en-us/library/bb531208.aspx

http://msdn.microsoft.com/en-us/library/bb531208.aspx