連載讓我們假設我有例如序列化水平的汽車類的一個對象內部和公共。公共級別的一些屬性不應該被序列化,因爲它們是內部的。決定其性能在運行時
此時的「最簡單」的方式,我能想到的實現這一目標是通過繼承:
class CarPublic {
public int PropX {get;set}
}
class CarInternal: CarPublic {
public string PropY {get;set}
}
然後,我可以
object ToSerialize() {
CarInternal car = GetCar();
if(level == Level.Public) {
return car as CarPublic;
} else {
return car;
}
}
的ToSerialize的結果()被取由一個框架(我沒有 控制)並序列化爲JSON或XML。
我爲了簡化省略XML序列化屬性。
這感覺就像一個黑客和黑客帶你只有這麼遠。有沒有更好的方法(方法?)來實現這一目標?
我認爲它清除了,但我想避免編寫JSON和XML我自己的序列化方法。
在此先感謝 Tymek
==編輯
爲了澄清,我希望能夠序列化多層次:
class Car0 {
public int PropA {get;set}
}
class Car1: Car0 {
public string PropB {get;set}
}
class Car2: Car1 {
public int PropC {get;set}
}
class Car3: Car2 {
public string PropD {get;set}
}
和
object ToSerialize(Level level) {
Car3 car = GetCar();
switch(level) {
case Level.Zero: return car as Car0;
case Level.One: return car as Car1;
case Level.Two: return car as Car3;
case Level.Three: return car as Car4;
}
return null;
}
==選擇方法
我標誌着馬克Gravell的答案的答案,因爲它提供瞭如何C#泛型信息和它的「標準」的組件都支持我提出的要求。
但是我認爲對於我的問題最好的方法是使用如上所示的代理類,並且 使用以下方法在此多級模式中序列化類。
public interface ICar {
Car0 As0();
Car1 As1();
Car2 As2();
Car3 As3();
...
}
這允許保持Car0..3類非常簡單,只有性能,維護和理解。
編寫自定義序列化方法是我所知道的更好的方法(並且確實不是那麼困難)。你有自定義的序列化需求,它可以自己定製的序列化器...是否有一個特定的原因,你不想沿着這條路徑走下去? – Bill 2012-02-14 05:08:24
主要原因是我在框架環境中,序列化應該由框架完成,而我只是將結果作爲對象返回。 – mayu 2012-02-14 05:19:12
你能看到這個環境中的其他類正在做什麼來解決這個問題嗎?如果你要破解它,也可能像其他人一樣破解它:) – Bill 2012-02-14 05:40:50