我正在使用以下代码在C#文件中创建字典:
private readonly Dictionary<string, XlFileFormat> FILE_TYPE_DICT
= new Dictionary<string, XlFileFormat>
{
{"csv", XlFileFormat.xlCSV},
{"html", XlFileFormat.xlHtml}
};
Run Code Online (Sandbox Code Playgroud)
new错误下面有一条红线:
无法使用功能'集合initilializer',因为它不是ISO-2 C#语言规范的一部分
谁能解释一下这里发生了什么?
编辑:好的,所以事实证明我使用的是.NET版本2.
C#是否允许在单行表达式中填充哈希表?我正在考虑与以下Python相当的东西:
mydict = {"a": 23, "b": 45, "c": 67, "d": 89}
Run Code Online (Sandbox Code Playgroud)
换句话说,是否可以在单独的表达式中设置每个键值对?
有没有办法ViewDataDictionary用一行代码创建一个模型和附加属性.我试图RenderPartial在组装模型和一些额外的显示配置属性时调用强类型视图,而无需跨多行显式组装ViewDataDictionary.似乎有可能给出RenderPartial一个模型object和a 的重载,ViewDataDictionary但看起来它只是忽略了ViewDataDictionary它们都被填充.
// FAIL: This will result in ViewData being a ViewDataDictionary
// where Model = MyModelObject and there are no other parameters available.
this.Html.RenderPartial("SomePartialView", MyModelObject, new ViewDataDictionary(new { SomeDisplayParameter = true }));
Run Code Online (Sandbox Code Playgroud)
我发现其他人有同样的问题,但他们的解决方案是我发现的相同的多线概念:ViewDataDictionary用模型创建离散,添加新参数并在RenderPartial调用中使用它.
var SomeViewData = new ViewDataDictionary(MyModelObject);
SomeViewData.Add("SomeDisplayParameter", true);
this.Html.RenderPartial("SomePartialView", SomeViewData);
Run Code Online (Sandbox Code Playgroud)
我总是可以将这个逻辑包装成一个ChainedAdd方法,该方法返回一个重复的字典,并添加了新的元素,但似乎我错过了一些创建一个ViewDataDictionary可以为我做这个的方法(这比我希望的更多开销)对于).
this.Html.RenderPartial("SomePartialView", new ViewDataDictionary(MyModelObject).ChainedAdd("SomeDisplayParameter", true));
public static ViewDataDictionaryExtensions {
public static ViewDataDictionary ChainedAdd(this ViewDataDictionary source, …Run Code Online (Sandbox Code Playgroud) 如何使用集合初始化器初始化对象System.Collections.Generic.List?System.Collections.Generic.Dictionary