简体   繁体   中英

Why I can't use the name of the class as a type?

I'm using the XmlSerializer constructor that asks for a Type object:

XmlSerializer mySerializer = new XmlSerializer(typeof(MyClass));

Why is it not the same to use the name of the class as a type? Like this:

XmlSerializer mySerializer = new XmlSerializer(MyClass);

The first comment on this question is correct, but I think it can be further clarified with the practical reason.

MyClass is not something that can be executed on its own. Why? Because the c# compiler itself does not have code to translate 'MyClass' on something meaningful for the execution environment.

The first statement works because the constructor of XmlSerializer is expecting an instance of the class 'Type'. The typeof operator returns an instance of the class Type that contains information about the class 'MyClass'. The argument for the operator typeof(?) has to be a type known at compile time. The meaning of the operator 'typeof' is baked in the # compiler so that during compilation typeof(ClassName) will generate code that returns an instance of the 'Type' class containing information about the class specified (the argument). Because Type is just like any other class, you can even use typeof(Type).

The XmlSerializer constructor expects an instance of type System.Type for its parameter. The identifier MyClass doesn't correspond to an instance of anything; it's just the name of a class. The typeof keyword returns a System.Type instance that represents the type you specify (in this case, a System.Type instance that represents the MyClass class).

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