gpt4 book ai didi

c# - Xml反序列化为对象,反射为类型

转载 作者:行者123 更新时间:2023-12-04 14:01:37 26 4
gpt4 key购买 nike

我正在使用 Xml 来存储应用程序的设置,这些设置在运行时发生更改,并在应用程序执行期间多次序列化和反序列化。

有一个 Xml 元素可以包含任何可序列化类型,并且应该从 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”同名的属性,我的目的是设置 instrument.property = 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>

产生 “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 手动实例化对象并转换(在基元的情况下)或字符串解析属性和值(在非基元的情况下)?)

最佳答案

好吧,它走得太远了,但我认为我已经设法解决了这个问题。但解决方案并不是那么漂亮。因为它包括大量使用反射。 (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; }
}

我们还需要一个包含点类的根类:

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

关于c# - Xml反序列化为对象,反射为类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69831110/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com