2016-11-24 28 views
1

System.Globalization.CultureInfo類的集合的高速緩存在我的上下文包裝類類型,並沒有合同可以推斷出與.NET預定義類protobuf網

public Collection<System.Globalization.CultureInfo> Cultures 
{ 
    get 
    { 
     // Get the value from Redis cache 
    } 
    set 
    { 
     // Save the value into Redis cache 
    } 
} 

它可以通過訪問MyContextWrapper.Current.Cultures

我收到以下錯誤,而與protobuf-net序列化「收藏文化」的價值:

類型未預期,且沒有合同可以推斷:System.Globalization.CultureInfo

enter image description here

我知道protobuf-net在類上需要[ProtoContract]和[ProtoMember]裝飾,但這隻適用於自定義用戶定義的類。

我該如何去.NET預定義的類然後例如System.Globalization.CultureInfo在我的情況。

這甚至可能與protobuf網?

+0

你爲什麼要序列化文化信息? – Maarten

+0

我的回答對你有幫助嗎?讓我知道如果有什麼我應該補充的。 – Measuring

回答

1

你可以去一個代理。在序列化Collection之前通知它的protobuf-net。儘管我現在只能使用內置文化,但您可以自行擴展它以添加附加數據以完全恢復文化。

到的CultureInfo轉換成protobuf網支持的類型的替代品。

[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)); 

如果您還有其他問題,讓我知道了意見。

相關問題