代码之家  ›  专栏  ›  技术社区  ›  eKek0

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

  •  6
  • eKek0  · 技术社区  · 16 年前

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

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

    我该怎么做 在飞行中 ? 不创建字典变量。

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

    3 回复  |  直到 11 年前
        1
  •  39
  •   Robert Harvey    16 年前

    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

        2
  •  6
  •   Robert Harvey    16 年前

    下面的博客文章有一个助手方法,可以从匿名类型创建字典对象。

    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; 
       }
    
        3
  •  0
  •   John Saunders    16 年前

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

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