When I declare a class as internal, why does the IL show it as private?

落花浮王杯 提交于 2019-12-01 04:36:55

问题


If I declare a class as internal, why does the IL show it as private?

internal class Thing

.class private auto ansi beforefieldinit Thing.Thing
       extends [mscorlib]System.Object

回答1:


From IL's point of view, private means private to the assembly, i.e. internal in C#.

In C#, it is not possible to mark types as private if they are not nested. IL's equivalent accessibility for such types is nested private.

So we have:

  • C#'s internal -> IL's private (to the assembly)
  • C#'s private -> IL's nested private (to the enclosing type)



回答2:


On MSDN, it says:

The C# keywords protected and internal have no meaning in IL and are not used in the reflection APIs. The corresponding terms in IL are Family and Assembly. To identify an internal method using reflection, use the IsAssembly property. To identify a protected internal method, use the IsFamilyOrAssembly.

So I guess it just makes them private, since they can't be accessed from elsewhere.

EDIT: I see how my answer might not be completely correct, I just thought it was something worth noting. The MSDN article I linked has some interesting stuff on this "what code we write" - "what it becomes" relationship.




回答3:


The mapping of C# keywords to IL keywords isn't always a logical one. Ecma-335, section II.23.1.15 shows what flags are valid for a type. You'll see that it only defines Public, NotPublic and a set of NestedXxx flags. Nothing similar to "internal". So your class is actually NotPublic, displayed as "private" in ildasm.

It is easy to see a side-effect of this: try this declaration in your C# code:

private class DoesNotWork {
}

You'll get:

error CS1527: Elements defined in a namespace cannot be explicitly declared as private, protected, or protected internal



来源:https://stackoverflow.com/questions/18660300/when-i-declare-a-class-as-internal-why-does-the-il-show-it-as-private

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!