内联语句keypairvalues

本文关键字:keypairvalues 语句 | 更新日期: 2023-09-27 18:10:53

我有以下HtmlLink:

HtmlLink htmlLink = new HtmlLink(); 
htmlLink.Attributes.Add("href", "/style/" + category + ".css"); 
htmlLink.Attributes.Add("type", "text/css"); 
htmlLink.Attributes.Add("rel", "stylesheet"); 

我试着把它写在一行语句中,但是我不知道写这样的语句的正确语法:

List<string> list = new List<string> { "one", "two", "three" };
做:

HtmlLink htmlLink = new HtmlLink() { ???? };
有人能满足我的好奇心吗?

内联语句keypairvalues

据我所知,这是不可能的。您总是可以编写一个扩展方法:

public static void AddAttributes(this HtmlLink thisLink, IDictionary<string, string> attributes)
{
  foreach(var attribute in attributes.Keys)
  {
    thisLink.Attributes.Add(attribute.Key, attribute.Value);
  }
}

用法:

var link = new HtmlLink();
link.AddAttributes(new Dictionary<string,string>{{"Key1","Value1"},{"Key2","Value2"}};

不确定这比多次添加有多大的优势。另一个选择是在某个地方编写一个helper方法,它接受一个字典,并输出一个带有其属性集的HtmlLink。