问题
I noticed something curious when messing around with nested classes and outputting the name of the type to a console window. I was wondering if someone could explain it a bit for me. When calling GetType()
on the main class, it returns what I would expect, which was the name of the class after the relevant namespaces. i.e. Namespace.Namespace.Classname
However, when I call a function from within the enclosing class to return the type of the nested class I get the value returned as this:
Namespace.Namespace.ClassNameEnclosing + ClassNameNested.
Why is it not simply returned as dot notation. Why the + symbol? I am just curious as to what is going on in the background that causes this notation.
回答1:
Dots are used to denote namespaces. The nested class is still in the same namespace, it's just nested within a class.
I can't tell offhand (from a brief study of ECMA-335) whether an unqualified type name which included a dot would actually be valid in IL; I suspect it would, but it would make all kinds of diagnostics harder to read.
回答2:
Reflection is not language-specific.
The dot notation (Namespace.Namespace.OuterClassName.InnerClassName
) is specific to C#. Reflection must work for every language that you can use to compile to IL. Besides, how can you be sure, when reflecting, that the OuterClassName
isn't just another part of the namespace without examining other properties of the Type
class?
You ask why is it not simple returned as dot notation? You might as well ask "Why is it not simply returned as IronPython notation", or IronLisp notation, or L# notation, or BOo notation, or...
Learn the notation used in reflection, and you can use it to analyze code written in any language.
来源:https://stackoverflow.com/questions/9110744/nested-class-gettype