2016-03-01 46 views
0

我不得不處理,可以採取下列形式串行化的數據:複雜遺傳模式收縮

{ 
    "CommonKey" : "Value", 
    "ObjType" : "A", 
    "Obj" : { 
     "CommonObjKey" : "Value" 
     "ObjKey" : "Value" 
    } 
} 

OR

{ 
    "CommonKey" : "Value", 
    "ObjType" : "B", 
    "Obj" : { 
     "CommonObjKey" : "Value" 
     "ObjKey" : 1234 
    } 
} 

注意ObjKey可以是一個字符串或整數取決於類型。

如果超載派生的返回類型在C#允許的,這是它如何建模:

abstract class ContractBase 
{ 
    string CommonKey; 
    string ObjType; 
    abstract ObjBase Obj; 
} 

class AContract : ContractBase { override AObj Obj; } 
class BContract : ContractBase { override BObj Obj; } 

abstract class ObjBase { string CommonObjKey; } 

class AObj : ObjBase { string ObjKey; } 
class BObj : ObjBase { int ObjKey; } 

是否有這個數據模式模型推薦的方法是什麼?要求是:

  1. 我可以使用JSON.NET
  2. 我可以使用的基類型的90%的時間,只將其丟需要A或B-特定字段時容易反序列化。

回答

1

我會建議使用dyanmic爲一個屬性(ObjKey),沒有一致的類型。

可能的實現:

var cb1 = new ContractBase 
{ 
    CommonKey = "Value", 
    ObjType = "A", 
    Obj = new Obj 
    { 
     CommonObjKey = "Value", 
     ObjKey = 1234 
    } 
}; 

var cb2 = new ContractBase 
{ 
    CommonKey = "Value", 
    ObjType = "A", 
    Obj = new Obj 
    { 
     CommonObjKey = "Value", 
     ObjKey = "Value" 
    } 
}; 

class ContractBase 
{ 
    public string CommonKey { get; set; } 
    public string ObjType { get; set; } 
    public Obj Obj { get; set; } 
} 

class Obj 
{ 
    public string CommonObjKey { get; set; } 
    public dynamic ObjKey { get; set; } 
} 

請注意,您可以使用object代替dynamic,但dynamic減少了需要鑄造,這使得代碼更易讀,易懂。