gpt4 book ai didi

c# - 在自定义类型上使用集合初始化语法?

转载 作者:可可西里 更新时间:2023-11-01 08:55:21 26 4
gpt4 key购买 nike

我有一个很大的静态列表,它基本上是一个查找表,所以我用代码初始化了这个表。

private class MyClass
{
private class LookupItem
{
public int Param1 { get; set; }
public int Param2 { get; set; }
public float Param2 { get; set; }
public float Param4 { get; set; }
}

private static List<LookupItem> _lookupTable = new List<LookupItem>()
{
new LookupItem() { Param1 = 1, Param2 = 2, Param3 = 3 Param4 = 4 },
new LookupItem() { Param1 = 5, Param2 = 6, Param3 = 7 Param4 = 8 },
//etc
}
}

真实LookupItem有更多的属性,所以我添加了一个构造函数以允许更紧凑的初始化格式:

private class MyClass
{
private class LookupItem
{
public int Param1 { get; set; }
public int Param2 { get; set; }
public float Param2 { get; set; }
public float Param4 { get; set; }

public LookupItem(int param1, int param2, float param3, float param4)
{
Param1 = param1;
Param2 = param2;
Param3 = param3;
Param4 = param4;
}
}

private static List<LookupItem> _lookupTable = new List<LookupItem>()
{
new LookupItem(1, 2, 3, 4),
new LookupItem(5, 6, 7, 8),
//etc
}
}

我真正想做的是为对象本身使用集合初始化程序格式,这样我就可以摆脱 new LookupItem()在每一行。例如:

private static List<LookupItem> _lookupTable = new List<LookupItem>()
{
{ 1, 2, 3, 4 },
{ 5, 6, 7, 8 },
//etc
}

这可能吗?我喜欢认为这是因为 KeyValuePairDictionary<>可以这样初始化。

MSDN状态:

Collection initializers let you specify one or more element intializers when you initialize a collection class that implements IEnumerable. The element initializers can be a simple value, an expression or an object initializer. By using a collection initializer you do not have to specify multiple calls to the Add method of the class in your source code; the compiler adds the calls.

这是否意味着我需要实现 IEnumerable在我的 LookupItem类并返回每个参数?不过我的课不是收藏课。

最佳答案

我认为您需要创建一个自定义集合而不是 List。例如,将其称为 LookupItemTable。为该集合提供一个 Add(int, int, float, float) 方法并让它实现 IEnumerable。例如:

class LookupItem
{
public int a;
public int b;
public float c;
public float d;
}

class LookupItemTable : List<LookupItem>
{
public void Add(int a, int b, float c, float d)
{
LookupItem item = new LookupItem();
item.a = a;
item.b = b;
item.c = c;
item.d = d;
Add(item);
}
}

private static LookupItemTable _lookupTable = new LookupItemTable {
{ 1, 2, 3, 4 },
{ 5, 6, 7, 8 }
};

我现在已经尝试了上面的代码,它似乎对我有用。

关于c# - 在自定义类型上使用集合初始化语法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9194363/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com