C#中“ this”的含义是什么? [英] What's the meaning of 'this' in C#?

查看:214
本文介绍了C#中“ this”的含义是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在通过C#执行CLR的第170页上:

At page.170 of 'CLR via C#':

public sealed class Program {
    public Int32 GetFive() { return 5; }
    public static void Main() {
       Program p = null;
       Int32 x = p.GetFive(); // In C#, NullReferenceException is thrown
    }
}

从理论上讲,上面的代码很好。当然,变量p为null,但是在调用非虚拟
方法(GetFive)时,CLR仅需要知道p的数据类型,即Program。如果确实调用了
GetFive,则此参数的值为null。由于在GetFive方法中未使用参数
,因此不会引发NullReferenceException。

Theoretically, the code above is fine. Sure, the variable p is null, but when calling a nonvirtual method (GetFive), the CLR needs to know just the data type of p, which is Program. If GetFive did get called, the value of the this argument would be null. Since the argument is not used inside the GetFive method, no NullReferenceException would be thrown.

对不起,我很愚蠢。我记得CLR通过'this'定位真正的方法代码,它总是隐式地适用于方法delcare的第一个参数,为什么它说'在调用非虚拟
方法(GetFive)时,CLR只需要知道数据类型的p'?

Pardon my stupid. I remember that CLR locate really method code by 'this' which always implictly appares at the first argument in method delcare, why it says 'when calling a nonvirtual method (GetFive), the CLR needs to know just the data type of p' ?

推荐答案

CLR不会对非虚拟方法进行null检查。基本上,如果使用 call 指令调用方法,则CLR不会检查空的 this 指针。相反, callvirt 指令始终检查无效性。但是,无论该方法是否为虚拟方法,C#都会发出 callvirt 指令。

The CLR doesn't do null checks for non-virtual methods. Basically, if a method is called with the call instruction, the CLR does not check for a null this pointer. In contrast, the callvirt instruction always checks for nullity. However, C# emits the callvirt instruction whether or not the method is virtual.

这段话是说,如果C#编译器发出了语义上更合适的 call 指令,而不是 callvirt 指令用于非虚拟方法,则所讨论的代码不会抛出 NullReferenceException 。我记得,编译器团队决定几乎总是发出 callvirt 指令,因为它更好地处理了版本控制(而且JIT可以优化 callvirt 调用 )。

What the passage is saying is that if the C# compiler emitted the more semantically appropriate call instruction rather than callvirt instruction for non-virtual methods, then the code in question would not throw a NullReferenceException. As I recall, the compiler team decided to almost always emit the callvirt instruction because it handled versioning better (also the JIT can optimize a callvirt into a call).

请参见 http://www.pvle.be/tag/clr/

这篇关于C#中“ this”的含义是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆