当try 使用.NET 6从appSettings.json获取配置中的集合时,我遇到了一个奇怪的行为.

我的班级:

public record SomeOptions
{
    public IReadOnlyCollection<string> SomeColl { get; init; } = new List<string> { "wrongString" };
}

我的appcastings.json:

{
  "Some": {
    "SomeColl": [ "expectedString" ]
  }
}

然后我try 获得这样的值:

var section = configuration.GetSection("Some");
var options = section.Get<SomeOptions>();

我从属性(world-String)获得了默认值.但如果改变属性就像:

public record SomeOptions
{
    public IReadOnlyCollection<string> SomeColl { get; init; } = null!;
}

public record SomeOptions
{
    public ICollection<string> SomeColl { get; init; } = new List<string>();
}

我从appsettings.json(expected字符串)中获得了值.有人能解释一下--为什么会发生这种情况吗?

推荐答案

the source code部分涵盖:

if (config.GetChildren().Any())
{
    // 对于数组和只读列表类接口,如果可以的话,我们将连接到已经存在的内容
    if (type.IsArray || IsImmutableArrayCompatibleInterface(type))
    {
        if (!bindingPoint.IsReadOnly)
        {
            bindingPoint.SetValue(BindArray(type, (IEnumerable?)bindingPoint.Value, config, options));
        }

        // for getter-only collection properties that we can't add to, nothing more we can do
        return;
    }

对于数组和只读列表类接口,如果可以的话,我们将连接到已经存在的内容

尽管我找不到这一点被记录下来.

您可以try 将其报告@github,但很可能它不会被视为 destruct 性变更.

我的猜测是这样做是为了支持分层格式(即当数组元素在多个配置源中定义时,但不确定这是否是一个好主意,有时会导致意外行为).

Csharp相关问答推荐

错误NU 1301:无法加载源的服务索引

C#使用属性和值将JSON转换为XML

为什么EF Core 6会针对null验证Count(*)?

图形API基于appid列表检索多个应用程序

如何将不同类型的扩展参数的javascript函数转换成C#风格?

Thad.Sept()vs Task.Delay().Wait()

尽管保证密钥不同,但已添加相同密钥的项(&Q;)

Rx.Net窗口内部可观测数据提前完成

共享暂存/生产环境中Azure事件中心的建议配置

Unix上的.NET(核心):.NET意外地未看到通过P/Invoke系统调用对环境变量进行的进程内修改

net中从位图获取坐标和绘制折线

Lambda表达式如何与隐式强制转换一起工作?

EF核心新验证属性`DeniedValues`和`StringCompison`不起作用

在DoubleClick上交换DataGridViewImageColumn的图像和工具提示

在等待OnGetAsync时打开Razor Page显示微调器

将J数组转换为列表,只保留一个嵌套的JToken

C#命名管道-编码错误?

如何在单击按钮后多次异步更新标签

嵌套Blazor组件内的验证

为什么我不能在固定语句中使用外部函数?