问题描述
我用私人和公共方法所有的时间。不过,我不明白为什么他们的工作。创建一个小的Hello World程序:
I use private and public methods all the time. However, I do not understand why they work.Creating a small Hello World Program:
public class CallPublicHelloWorld
{
public void CallHelloWorld()
{
publicHelloWorld();
privateHelloWorld();
}
private void privateHelloWorld()
{
Console.WriteLine("Hello World");
}
public void publicHelloWorld()
{
Console.WriteLine("Hello World");
}
}
的IL为市民创建方式:
The IL created for the public method:
IL_0000: nop
IL_0001: ldstr "Hello World"
IL_0006: call void [mscorlib]System.Console::WriteLine(string)
IL_000b: nop
IL_000c: ret
的IL为私有方法创建的:
The IL created for the private method:
IL_0000: nop
IL_0001: ldstr "Hello World"
IL_0006: call void [mscorlib]System.Console::WriteLine(string)
IL_000b: nop
IL_000c: ret
这是完全一样的。
It's the exact same.
如何进行JIT区分和验证私有/公共规则被遵守?
How does the JIT differentiate and verify that the private/public rules were followed?
推荐答案
您省略了从生成白细胞介素的相关线路:
You omitted the relevant lines from the generated IL:
.method private hidebysig instance void privateHelloWorld () cil managed
.method public hidebysig instance void publicHelloWorld () cil managed
而这一切就是这么简单。请参阅本通用类型系统一> MSDN页面。
在重整的IL调用私有方法和ILASM编译它,在运行时你会得到:
When mangling the IL to call the private method and compiling it with ilasm, at runtime you'll get:
未处理的异常:System.MethodAccessException:尝试通过法Program.Main(System.String [])访问方法CallPublicHelloWorld.privateHelloWorld()'失败
在Program.Main(字串[] args)
at Program.Main(String[] args)
于是就有的是的运行时执行的辅助检查。
So there is an accessibility check performed by the runtime.
这篇关于如何C#验证C#私有定义?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!