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

C#如何限制Serialize扩展方法仅支持序列化泛型Dictionary对象

泛型字典专属序列化扩展方法实现

要实现仅允许泛型字典实例传入的序列化扩展方法,不需要做运行时类型判断,直接通过泛型参数的编译期约束就能实现,调整后的方案如下:

调整后代码

using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;

public static class DictionarySerializationExtensions
{
    public static byte[] Serialize<TKey, TValue>(this IDictionary<TKey, TValue> source)
    {
        try
        {
            if (source == null)
            {
                return null;
            }

            using (var memoryStream = new MemoryStream())
            {
                var binaryFormatter = new BinaryFormatter();
                binaryFormatter.Serialize(memoryStream, source);
                return memoryStream.ToArray();
            }
        }
        catch
        {
            return default(byte[]);
        }
    }
}

方案说明

  • 采用双泛型参数<TKey, TValue>,将扩展方法的源参数类型约束为IDictionary<TKey, TValue>,所有键值类型自定义的泛型字典(包括你提到的Dictionary<int, string>、Dictionary<foo, int>,以及自定义实现了该泛型接口的字典类)都可以正常调用该方法,非字典类型在编译阶段就会报错,无法传入,完全符合类型限制要求。
  • 如果使用自定义类(比如示例中的foo)作为字典键,需要给该类添加[Serializable]特性,否则BinaryFormatter序列化过程会抛出异常。
  • 注意:BinaryFormatter在.NET 5及以上版本、.NET Core平台中已被微软标记为存在安全风险的非推荐使用组件,如果是生产环境新项目,建议替换为System.Text.Json、MessagePack等更安全的序列化库实现。

内容的提问来源于stack exchange,提问作者bergungsdackel

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.03 02:39:24