问题
There are numerous examples on the web that show how to use the CodeDomSerializer. Most of them show how to override the Serialize and Deserialize methods of that class. The problem is that this Serialize method takes a manager argument of type IDesignerSerializationManager. I cannot figure out how to create an instance of that type...
Here's what I tried:
var root = new Form();
root.Controls.Add(new TextBox()
{
Text = "hello"
});
Type rootSerializerType = Type.GetType("System.ComponentModel.Design.Serialization.RootCodeDomSerializer, System.Design, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", true);
var rootSerializer = Activator.CreateInstance(
rootSerializerType,
BindingFlags.CreateInstance | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance,
null,
null,
null) as CodeDomSerializer;
IDesignerSerializationManager manager = new DesignerSerializationManager();
var serializationResult = (CodeTypeDeclaration)rootSerializer.Serialize(manager, root);
Because my manager object is not properly initialized, when I call the Serialize method as shown above, this exception is thrown:
[System.InvalidOperationException] "This method cannot be invoked because the serialization manager does not have an active serialization session."
I have googled and checked StackOverflow and I can't find any help on how to properly initialize the manager object ahead of my .Serialize invokation.
Any ideas?
回答1:
You need to create the section. Change last two lines to:
DesignerSerializationManager manager = new DesignerSerializationManager();
using (var session = manager.CreateSession())
{
var serializationResult = (CodeTypeDeclaration)rootSerializer.Serialize(manager, root);
// handle the result here
}
Use either the concrete class DesignerSerializationManager or var, because the IDesignerSerializationManager interface does not have the CreateSession method.
来源:https://stackoverflow.com/questions/47290751/serialization-with-codedomserializer-how-to-initialize-manager-object