C# 不应为类型,并且无法使用protobuf NET的.NET预定义类推断任何协定

C# 不应为类型,并且无法使用protobuf NET的.NET预定义类推断任何协定,c#,asp.net,.net,protobuf-net,C#,Asp.net,.net,Protobuf Net,我在上下文包装器类中有一个类集合的缓存 public Collection<System.Globalization.CultureInfo> Cultures { get { // Get the value from Redis cache } set { // Save the value into Redis cache } } 公共收藏文化 { 得到 { //从Redis缓存中获取值 } 设置

我在上下文包装器类中有一个类集合的缓存

public Collection<System.Globalization.CultureInfo> Cultures
{
    get
    {
        // Get the value from Redis cache
    }
    set
    {
        // Save the value into Redis cache
    }
}
公共收藏文化
{
得到
{
//从Redis缓存中获取值
}
设置
{
//将值保存到Redis缓存中
}
}
可以通过MyContextWrapper.Current.Cultures访问它

使用序列化“集合区域性”的值时,我遇到以下错误:

类型不应为,并且无法推断任何契约:System.Globalization.CultureInfo

我知道protobuf net需要在类上进行[ProtoContract]和[ProtoMember]修饰,但这仅适用于自定义用户定义的类

如何使用.NET预定义类,例如System.Globalization.CultureInfo


这在protobuf网络中是否可行

你可以找个代理。在序列化集合之前通知protobuf net。虽然我现在所说的只适用于内置的区域性,但您可以自己扩展它,添加额外的数据以完全恢复区域性

示例

将CultureInfo转换为protobuf net支持的类型的代理项

[ProtoContract]
public class CultureInfoSurrogate
{
    [ProtoMember(1)]
    public int CultureId { get; set; }

    public static implicit operator CultureInfoSurrogate(CultureInfo culture)
    {
        if (culture == null) return null;
        var obj = new CultureInfoSurrogate();
        obj.CultureId = culture.LCID;
        return obj;
    }

    public static implicit operator CultureInfo(CultureInfoSurrogate surrogate)
    {
        if (surrogate == null) return null;
        return new CultureInfo(surrogate.CultureId);
    }
}
将其放在程序开始的某个位置(至少在序列化集合之前):


如果您还有其他问题,请在评论中告诉我。

为什么要序列化文化信息?我的回答对您有帮助吗?如果有什么需要补充的,请告诉我。
RuntimeTypeModel.Default.Add(typeof(CultureInfo), false).SetSurrogate(typeof(CultureInfoSurrogate));