[英]Change the name of the class being serialized in .Net?
我可以使用SerializationBinder
映射傳入的類名並覆蓋BindToType
方法,但我發現無法在序列化過程中更改類的名稱。 有可能嗎?
編輯:
我指的是使用System.Runtime.Serialization
的序列化,而不是System.Xml.Serialization
。
謝謝!
我不確定我是否關注你,但你可以使用XmlTypeAttribute。 然后,您可以通過反射輕松檢索其值。
[XmlType(Namespace = "myNamespaceThatWontChange",
TypeName = "myClassThatWontChange")]
public class Person
{
public string Name;
}
看一下這個:
http://msdn.microsoft.com/en-us/library/system.xml.serialization.xmltypeattribute%28VS.100%29.aspx
我發現我可以使用GetObjectData
函數中的SerializationInfo
對象,並更改AssemblyName
和FullTypeName
屬性,這樣當我反SerializationBinder
,我可以使用SerializationBinder
將自定義程序集和類型名稱映射回有效類型。 這是一個semple:
可序列化類:
[Serializable]
class MyCustomClass : ISerializable
{
string _field;
void MyCustomClass(SerializationInfo info, StreamingContext context)
{
this._field = info.GetString("PropertyName");
}
void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
{
info.AssemblyName = "MyCustomAssemblyIdentifier";
info.FullTypeName = "MyCustomTypeIdentifier";
info.AddValue("PropertyName", this._field);
}
}
SerializationBinder:
public class MyBinder : SerializationBinder
{
public override Type BindToType(string assemblyName, string typeName)
{
if (assemblyName == "MyCustomAssemblyIdentifier")
if (typeName == "MyCustomTypeIdentifier")
return typeof();
return null;
}
}
序列化代碼:
var fs = GetStream();
BinaryFormatter f = new BinaryFormatter();
f.Binder = new MyBinder();
var obj = (MyCustomClass)f.Deserialize(fs);
反序列化代碼:
var fs = GetStream();
MyCustomClass obj = GetObjectToSerialize();
BinaryFormatter f = new BinaryFormatter();
f.Deserialize(fs, obj);
你可以用屬性來做:
[System.Xml.Serialization.XmlRoot("xmlName")]
public Class ClassName
{
}
看看使用代理+代理選擇器。 這與反序列化的綁定一起應該可以解決問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.