我使用 Xml 來存盤應用程式的設定,這些設定在運行時更改并在應用程式執行期間多次序列化和反序列化。
有一個 Xml 元素可以保存任何可序列化型別,并且應該從 type 屬性進行序列化和反序列化Object,即
[Serializable]
public class SetpointPoint
{
[XmlAttribute]
public string InstrumentName { get; set; }
[XmlAttribute]
public string Property { get; set; }
[XmlElement]
public object Value { get; set; }
} // (not comprehensive, only important properties displayed)
xml,
<?xml version="1.0" encoding="utf-8"?>
<StationSetpoints xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xsi:schemaLocation="http://www.w3schools.com StationSetpoints.xsd">
<Setpoint PartNumber="107983">
<Point InstrumentName="PD Stage" Property="SetPoint">
<Value xsi:type="xsd:string">3</Value>
</Point>
<Point InstrumentName="TR Camera" Property="MeasurementRectangle" StationSetpointMemberType="Property">
<Value xsi:type="xsd:string">{X=145,Y=114,Width=160,Height=75}</Value>
</Point>
</Setpoint>
</StationSetpoints>
我反序列化 Xml 并決議屬性以通過“InstrumentName”查找儀器物件,該儀器將具有與 Xml 屬性“Property”相同的屬性,我的目的是設定該儀器.property = Value 元素在 xml 中。使用反射轉換物件很簡單,例如(在 vb.net 中)
Dim ii = InstrumentLoader.Factory.GetNamed(point.InstrumentName)
Dim pi = ii.GetType().GetProperty(point.Property)
Dim tt = pi.PropertyType
Dim vt = Convert.ChangeType(point.Value, tt)
pi.SetValue(ii, vt)
是的,如果 point.Value 是一個物件,那會起作用,但它不是。從物件序列化的結果是一個字串。在屬性為 Double 的情況下,我們得到
<Value xsi:type="xsd:string">3</Value>
yield "3",并且當 System.Drawing.Rectangle 時,
<Value xsi:type="xsd:string">{X=145,Y=114,Width=160,Height=75}</Value>
產量 "{X=145,Y=114,Width=160,Height=75}"
那么有沒有辦法將值型別或物件的 Xml 表示形式直接轉換為 .NET 等價物?
(或者我必須使用 Reflection / System.Activator 手動實體化物件并轉換(在基元的情況下)或字串決議屬性和值(在非基元的情況下)?)
uj5u.com熱心網友回復:
好吧,它走得太遠了,但我認為我已經設法解決了這個問題。但解決方案并不那么漂亮。因為它包括大量使用反射。(IL 發射)
我構建了一個動態型別構建器,它擴展SetpointPoint和覆寫了Value屬性,以便您可以設定我在評論中提到的自定義屬性。它看起來像下面:
public class DynamicTypeBuilder
{
private static readonly MethodAttributes getSetAttr =
MethodAttributes.Public | MethodAttributes.Virtual | MethodAttributes.SpecialName |
MethodAttributes.HideBySig;
private static readonly AssemblyName aName = new AssemblyName("DynamicAssemblyExample");
private static readonly AssemblyBuilder ab =
AssemblyBuilder.DefineDynamicAssembly(
aName,
AssemblyBuilderAccess.Run);
private static readonly ModuleBuilder mb =
ab.DefineDynamicModule(aName.Name ".dll");
public Type BuildCustomPoint(Type valueType)
{
var tb = mb.DefineType(
"SetpointPoint_" valueType.Name,
TypeAttributes.Public, typeof(SetpointPoint));
var propertyBuilder = tb.DefineProperty("Value",
PropertyAttributes.HasDefault,
typeof(object),
null);
var fieldBuilder = tb.DefineField("_value",
typeof(object),
FieldAttributes.Private);
var getBuilder =
tb.DefineMethod("get_Value",
getSetAttr,
typeof(object),
Type.EmptyTypes);
var getIL = getBuilder.GetILGenerator();
getIL.Emit(OpCodes.Ldarg_0);
getIL.Emit(OpCodes.Ldfld, fieldBuilder);
getIL.Emit(OpCodes.Ret);
var setBuilder =
tb.DefineMethod("set_Value",
getSetAttr,
null,
new Type[] { typeof(object) });
var setIL = setBuilder.GetILGenerator();
setIL.Emit(OpCodes.Ldarg_0);
setIL.Emit(OpCodes.Ldarg_1);
setIL.Emit(OpCodes.Stfld, fieldBuilder);
setIL.Emit(OpCodes.Ret);
// Last, we must map the two methods created above to our PropertyBuilder to
// their corresponding behaviors, "get" and "set" respectively.
propertyBuilder.SetGetMethod(getBuilder);
propertyBuilder.SetSetMethod(setBuilder);
var xmlElemCtor = typeof(XmlElementAttribute).GetConstructor(new[] { typeof(Type) });
var attributeBuilder = new CustomAttributeBuilder(xmlElemCtor, new[] { valueType });
propertyBuilder.SetCustomAttribute(attributeBuilder);
return tb.CreateType();
}
}
對您的類稍作修改是將Value屬性設為虛擬,以便在動態型別中我們可以覆寫它。
[XmlElement]
public virtual object Value { get; set; }
這是什么DynamicTypeBuilder做的僅僅是產生于這樣的飛行類:
public class SetpointPoint_Double : SetpointPoint
{
[XmlElement(typeof(double))]
public override object Value { get; set; }
}
我們還需要一個包含 Point 類的根類:
[Serializable]
public class Root
{
[XmlElement("Point")]
public SetpointPoint Point { get; set; }
}
這就是我們測驗代碼的方式:
var builder = new DynamicTypeBuilder();
var doublePoint = builder.BuildCustomPoint(typeof(double));
var pointPoint = builder.BuildCustomPoint(typeof(Point));
var rootType = typeof(Root);
var root = new Root();
var root2 = new Root();
var instance1 = (SetpointPoint)Activator.CreateInstance(doublePoint);
var instance2 = (SetpointPoint)Activator.CreateInstance(pointPoint);
instance1.Value = 1.2;
instance2.Value = new Point(3, 5);
root.Point = instance1;
root2.Point = instance2;
// specifying used types here as the second parameter is crucial
// DynamicTypeBuilder can also expose a property for derived types.
var serialzer = new XmlSerializer(rootType, new[] { doublePoint, pointPoint });
TextWriter textWriter = new StringWriter();
serialzer.Serialize(textWriter, root);
var r = textWriter.ToString();
/*
output :
<?xml version="1.0" encoding="UTF-8"?>
<Root xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<Point xsi:type="SetpointPoint_Double">
<Value xsi:type="xsd:double">1.2</Value>
</Point>
</Root>
*/
textWriter.Dispose();
textWriter = new StringWriter();
serialzer.Serialize(textWriter, root2);
var x = textWriter.ToString();
/*
output
<?xml version="1.0" encoding="UTF-8"?>
<Root xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<Point xsi:type="SetpointPoint_Point">
<Value xsi:type="Point">
<X>3</X>
<Y>5</Y>
</Value>
</Point>
</Root>
*/
var d = (Root)serialzer.Deserialize(new StringReader(x));
var d2 = (Root)serialzer.Deserialize(new StringReader(r));
PrintTheValue(d);
PrintTheValue(d2);
void PrintTheValue(Root r)
{
// you can use reflection here
if (r.Point.Value is Point p)
{
Console.WriteLine(p.X);
}
else if (r.Point.Value is double db)
{
Console.WriteLine(db);
}
}
uj5u.com熱心網友回復:
我決定允許序列化器將類(在 Rectangle 的情況下它是一個 Struct)序列化為具有屬性名稱和值對的字串,如圖 ie 所示{X=145,Y=114,Width=160,Height=75},原始型別為值 ie 3。
然后將此 Xml 表示決議為可以迭代的對,并相應地設定屬性和欄位。必須使用裝箱結構進行一些操作,因為裝箱時它們的底層型別似乎無法識別,因此使用 vb 中的解決方案Dim boxed As ValueType(歸功于此評論)
Dim ii = InstrumentLoader.Factory.GetNamed(point.InstrumentName)
Dim pi = ii.GetType().GetProperty(point.Property)
Dim tt = pi.PropertyType
If valueString.StartsWith("{") Then
Dim instance = CTypeDynamic(Activator.CreateInstance(tt), tt)
Dim instanceType = instance.GetType()
Dim boxed As ValueType = CType(instance, ValueType)
Dim propertiesAndValues =
valueString.Replace("{", "").Replace("}", "").Split(","c).
ToDictionary(Function(s) s.Split("="c)(0), Function(s) s.Split("="c)(1))
For Each p In instanceType.GetProperties()
If propertiesAndValues.ContainsKey(p.Name) Then
Dim t = p.PropertyType
Dim v = Convert.ChangeType(propertiesAndValues(p.Name), t)
p.SetValue(boxed, v, Nothing)
End If
Next
For Each f In instanceType.GetFields()
If propertiesAndValues.ContainsKey(f.Name) Then
Dim t = f.FieldType
Dim v = Convert.ChangeType(propertiesAndValues(f.Name), t)
f.SetValue(boxed, v)
End If
Next
pi.SetValue(ii, boxed)
Else
Dim vt1 = Convert.ChangeType(valueString, tt)
pi.SetValue(ii, vt1)
End If
我還沒有在 XmlSerializable 類(而不是結構)上嘗試過這個,但正在開發中。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/352823.html
