简体   繁体   中英

XmlSerializer & Activator.CreateInstance()

Okay, we all know that it is not possible to use the XmlSerializer for classes without a parameterless constuctor as the deserializer will create the object and set all properties. However, by using Activator.CreateInstance() one can instanciate classes without a parameterless constructor. For example we could instanciate the following class:

public class Foo
{
    public Foo(string bar){}
}

That class can easily be instanciated with the Activator:

Activator.CreateInstance(typeof(Foo),"some string");

Unfortunantely 'Foo' cannot be serialized using the XmlSerializer as it has no parameterless constructor. Why is there no way to use the XmlSerializer like that:

new XmlSerializer(typeof(Foo)).Deserialize(stream,"some string");

Of course I could implement my own Serializer that simply will store the type and all properites & fields of an object and then will use the Activator to instanciate the object and set the previously stores properties. The question is: would that make sense? I guess there must be a strong reason against because otherwise that would be implemented already, right?!?

XmlSerializer works via C# code-generation and dynamic compilation; because it uses the C# compiler, it is necessary that the code it generates would compile - noting that it must follow the rules as a separate assembly (no internal or private access).

Basically, it wants to use new Foo() , because it literally emits the C# code "new Foo()" which is fed to the compiler.

Yes, it could have chosen to use a different instantiation technique, but: new Foo() is the authors chose to go with - and it is a reasonable default.

Some other serializers choose to use Activator , and others still use sneaky IL techniques that provide direct access to non-public methods without any indirection.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM