gpt4 book ai didi

asp.net-mvc-2 - 如何为字典提供硬编码值

转载 作者:行者123 更新时间:2023-12-05 03:15:58 25 4
gpt4 key购买 nike

这是我的字典。

Dictionary<string, Test> test = new Dictionary<string, Test>();

在测试中,我有 Id、Name、Score。我想用硬编码值填充这些属性。(不止一个计数)。

如何给字典赋予静态值

我是否应该这样给予...

Dictionary<string, Test> test= new Dictionary<string, Test>();
Groups groups = new Groups();
groups.Id = "1";
groups.Name = "Name";
groups.Description = "Desc";
test.Add(groups.Id, groups);

最佳答案

您可以在 C#3 和 4 中使用集合初始化语法:

var data = new Dictionary<String,Object> {
{ "Foo", "Bax" },
{ "Bar", new DateTime(2010,10,10) },
{ "Xyzzy", 42 }
};

附加:更新后的问题代码:

Dictionary<string, Test> test= new Dictionary<string, Test>();
Groups groups = new Groups();
groups.Id = "1";
groups.Name = "Name";
groups.Description = "Desc";
test.Add(groups.Id, groups);

可以重写为单个表达式(同时注意值类型似乎是 Groups,并显示如何添加多个键值对):

Dictionary<string, Test> test= new Dictionary<string, Groups> {
{
"1", new Groups {
Id = "1",
Name = "Name",
Description = "Desc"
}
}, {
"2", new Groups {
Id = "2",
Name = "Another Name",
Description = "Something }
}
};

关于asp.net-mvc-2 - 如何为字典提供硬编码值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4860545/

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