gpt4 book ai didi

c# - 这种类型的 C# 编码语法称为什么,它在做什么?

转载 作者:行者123 更新时间:2023-12-01 22:51:12 25 4
gpt4 key购买 nike

对于下面的代码,特别是似乎没有连接到任何东西的 {},调用的语法是什么,它在做什么?

什么时候/为什么我可以在使用此语法时省略 ()

var a = new OpenApiSecurityRequirement() // Can I omit () and when/why?
{
{ // What is this doing?
new OpenApiSecurityScheme
{
Reference = new OpenApiReference
{
Type = ReferenceType.SecurityScheme,
Id="Bearer"
}
},
new string[]{}
} // What is this doing?
};

最佳答案

最外层的花括号只是一个 collection initialiser .

因为OpenApiSecurityRequirementAdd方法有两个参数,所以存在“似乎没有连接到任何东西”的内花括号。

您肯定已经在 Dictionary 中看到过这种语法:

new Dictionary<string, string>() {
{ "key1", "value1" },
{ "key2", "value2" },
{ "key3", "value3" }
};

假设this OpenApiSecurityRequirement,这也是一个 IDictionary,您的代码就是这样,但是内部大括号写在多行上。字典只有一个词条。键是OpenApiSecurityScheme,值是空字符串数组。

是的,括号可以省略。

脱糖:

var a = new OpenApiSecurityRequirement();
a.Add(
new OpenApiSecurityScheme
{
Reference = new OpenApiReference
{
Type = ReferenceType.SecurityScheme,
Id="Bearer"
}
},
new string[]{}
);

关于c# - 这种类型的 C# 编码语法称为什么,它在做什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74350818/

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