首页 > 解决方案 > 使用简短的初始化语法来初始化对值列表

问题描述

我在玩 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

标签: c#initializer-list

解决方案


作为迈克尔的答案的替代方案,并且为了避免使用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)
};

推荐阅读