c# - 使用简短的初始化语法来初始化对值列表
问题描述
我在玩 Space Engineers,这是一款允许在游戏中编写脚本的游戏。我想编写一个脚本,用某些物品类型重新装满一艘船。
原始代码只有项目名称列表:
public readonly List<RequiredItem> requiredItemNames = new List<String>{
"ilder_Component/Construction",
"nt/Computer",
"_Component/Girder",
"ponent/MetalGrid",
"Motor",
"MyObjectBuilder_Component/SteelPlate",
};
但我想为不同的项目检索不同的金额。我准备了以下结构类:
public class RequiredItem {
public RequiredItem(string pattern, double req) {
this.pattern = pattern;
this.amountRequired = req;
}
string pattern;
double amountRequired = 0;
}
我想在没有重复的情况下初始化列表new RequiredItem("name", 12345)
。我从 C++ 中知道这种语法,但从 C# 中却不知道。我尝试了以下方法:
public readonly List<RequiredItem> requiredItemNames = new List<String>{
{"ilder_Component/Construction", 300}, // construction comp
{"nt/Computer",150},
{"_Component/Girder",100},
{"ponent/MetalGrid",70},
{"Motor",150},
{"MyObjectBuilder_Component/SteelPlate",333}
};
这给了我错误:
Error: No oveload for method 'Add' takes 2 arguments
所以我想它试图把对List.Add
而不是我的构造函数放入。我如何确定我想要构建然后放入的项目Add
?
解决方案
作为迈克尔的答案的替代方案,并且为了避免使用Builder
方法,您还可以依赖使用 C#隐式关键字,例如:
public class RequiredItem
{
//snip
public static implicit operator RequiredItem((string pattern, double req) ri)
{
return new RequiredItem(ri.pattern, ri.req);
}
}
现在您可以使用元组创建列表:
public readonly List<RequiredItem> requiredItemNames = new List<RequiredItem>
{
("ilder_Component/Construction", 300), // construction comp
("nt/Computer",150),
("_Component/Girder",100),
("ponent/MetalGrid",70),
("Motor",150),
("MyObjectBuilder_Component/SteelPlate",333)
};
推荐阅读
- workflow - Github 操作未上传工件
- powershell-3.0 - 用引号和斜杠替换字符串
- python - 正则表达式 - re.sub 解释
- sql - 在 wordpress 网站上以一段文本显示 SQL 查询结果的最简单方法?
- postgresql - 在函数参数中允许可变未知数
- asp.net-core - 从 AAD .net 核心应用程序获取 oauth 令牌?
- node.js - 为什么 var 不设置全局变量?
- ruby - 当 gem 列表的括号中列出同一个 gem 的两个版本时,这意味着什么?
- docker - 詹金斯。并行运行 docker 容器(声明式)
- regex - RegEx 在 Google Data Studio 中清理和合并电子邮件活动