什么"这&Q​​UOT;意思是在静态方法声明? [英] What does "this" mean in a static method declaration?

查看:228
本文介绍了什么"这&Q​​UOT;意思是在静态方法声明?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经看到了使用关键字在函数的参数声明部分code。例如:

I've seen some code that uses the keyword this in the function parameter declaration. For example:

public static Object SomeMethod( this Object blah, bool blahblah)

这个词是什么意味着在这方面?

推荐答案

这意味着的someMethod()是的扩展方法对象类。

定义后,你可以调用任何对象这个方法情况下(尽管它被宣布静态)一样,因此:

After defining it you can call this method on any Object instances (despite it being declared static), like so:

object o = new Object();
bool someBool = true;

// Some other code...

object p = o.SomeMethod(someBool);

这个对象参数是指你在调用它的对象,实际上不是在参数表中找到。

The this Object parameter refers to the object you call it on, and is not actually found in the parameter list.

为什么它宣布其原因静态,而你把它像一个实例方法是因为编译器是在IL一个真正的静态调用。那深藏下来了,所以我就不细说了,但同时也意味着你可以调用它,就好像它是任何静态方法:

The reason why it's declared static while you call it like an instance method is because the compiler translates that to a real static call in the IL. That goes deep down though, so I shan't elaborate, but it also means you can call it as if it were any static method:

object o = new Object();
bool someBool = true;

// ...

object p = ObjectExtensions.SomeMethod(o, someBool);

这篇关于什么"这&Q​​UOT;意思是在静态方法声明?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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