当尝试从 appsettings.json 获取配置中的集合时,我遇到了奇怪的行为。
我的班级:
public record SomeOptions
{
public IReadOnlyCollection<string> SomeColl { get; init; } = new List<string> { "wrongString" };
}
我的appsettings.json:
{
"Some": {
"SomeColl": [ "expectedString" ]
}
}
然后我尝试获取这样的值:
var section = configuration.GetSection("Some");
var options = section.Get<SomeOptions>();
我从属性中获得了默认值(错误的字符串)。但如果将属性更改为:
public record SomeOptions
{
public IReadOnlyCollection<string> SomeColl { get; init; } = null!;
}
或者
public record SomeOptions
{
public ICollection<string> SomeColl { get; init; } = new List<string>();
}
我从
appsettings.json
(expectedString)获得了价值。有人可以解释一下 - 为什么会发生这种情况?谢谢。
这部分源代码涵盖:
// for arrays and read-only list-like interfaces, we concatenate on to what is already there, if we can
if (config.GetChildren().Any())
{
// for arrays and read-only list-like interfaces, we concatenate on to what is already there, if we can
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;
}
虽然我找不到这个记录。
我猜测这样做是为了支持分层配置(即当在多个配置源中定义数组元素时,尽管不确定这也是一个好主意)。