You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在.NET Core中将appsettings.json配置段加载到HashSet中

报错原因

.NET 配置绑定系统默认对JSON数组的绑定目标为List<T>,没有内置ISet<T>/HashSet<T>类型的直接绑定支持,因此会触发类型转换异常。

解决方案

方案1:手动转换(最简便,无需额外扩展)

方式1:绑定时手动赋值

无需修改原有配置类定义,读取配置时先拿到列表再转成HashSet赋值即可:

var appSettingsSection = Configuration.GetSection("AppSettings");
var bList = appSettingsSection.GetValue<List<string>>("B") ?? Enumerable.Empty<string>();
var appSetting = new AppSetting
{
    B = new HashSet<string>(bList)
};
// 注册IOptions的写法
services.Configure<AppSetting>(opt => 
{
    opt.B = new HashSet<string>(appSettingsSection.GetValue<List<string>>("B") ?? Enumerable.Empty<string>());
});

方式2:修改配置类兼容默认绑定

修改配置类的属性实现,内部兼容List和ISet的转换,原有绑定代码无需改动:

public class AppSetting
{
    private List<string> _bStorage;
    public ISet<string> B 
    { 
        get => new HashSet<string>(_bStorage ?? Enumerable.Empty<string>());
        set => _bStorage = value?.ToList();
    }
}

方案2:全局自定义转换器(适合项目中存在大量ISet类型配置的场景)

实现自定义配置转换器,全局支持所有ISet<T>/HashSet<T>属性的自动绑定:

  1. 先实现转换器类:
using System.Globalization;
using Microsoft.Extensions.Configuration;

public class HashSetConfigurationConverter : ConfigurationConverterBase
{
    public override bool CanConvert(Type typeToConvert)
    {
        if (!typeToConvert.IsGenericType) return false;
        var genericDef = typeToConvert.GetGenericTypeDefinition();
        return genericDef == typeof(ISet<>) || genericDef == typeof(HashSet<>);
    }

    public override object ConvertFrom(CultureInfo culture, object value, Type destinationType)
    {
        if (value is IEnumerable<string> strEnumerable)
        {
            var elementType = destinationType.GetGenericArguments()[0];
            var hashSetType = typeof(HashSet<>).MakeGenericType(elementType);
            return Activator.CreateInstance(hashSetType, strEnumerable);
        }
        return base.ConvertFrom(culture, value, destinationType);
    }
}
  1. 绑定时注册转换器即可:
var appSettingsSection = Configuration.GetSection("AppSettings");
var binderOptions = new BinderOptions
{
    Converters = { new HashSetConfigurationConverter() }
};
// 直接读取实例
AppSetting appSetting = appSettingsSection.Get<AppSetting>(binderOptions);
// 注册IOptions
services.Configure<AppSetting>(appSettingsSection, opt => 
{
    opt.Converters.Add(new HashSetConfigurationConverter());
});

内容的提问来源于stack exchange,提问作者Nguyễn Thành Nghĩa

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 15:45:01