“这个”是什么意思?在静态方法声明中意味着什么?
我见过一些在函数参数声明中使用关键字 this
的代码。例如:
public static Object SomeMethod( this Object blah, bool blahblah)
this
一词在该上下文中意味着什么?
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)
What does the word this
mean in that context?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这意味着
SomeMethod()
是一个扩展方法 到Object
类。定义后,您可以在任何
Object
实例上调用此方法(尽管它被声明为static
),如下所示:this Object
参数引用您调用它的对象,并且实际上在参数列表中找不到。当您像实例方法一样调用它时,它被声明为静态的原因是因为编译器将其转换为 IL 中真正的静态调用。这虽然很深入,所以我不会详细说明,但这也意味着您可以像调用任何静态方法一样调用它:
It means
SomeMethod()
is an extension method to theObject
class.After defining it you can call this method on any
Object
instances (despite it being declaredstatic
), like so:The
this Object
parameter refers to the object you call it on, and is not actually found in the parameter list.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:这是声明扩展方法的方式。
这意味着您可以使用
.SomeMethod
为任何对象调用 SomeMethod。.
之前的对象将是 blah 参数。扩展方法可用于从
this
参数类型继承的所有类型(在本例中为对象)。如果您有SomeMethod(this IEnumerableenumerable)
,它将在所有IEnumerable
:s 上可用,例如List
。It is how you declare an extension method.
This means that you can invoke SomeMethod with
.SomeMethod
for any object. The object before the.
will be the blah parameter.The extension method will be available on all types inheriting from the type of the
this
parameter, in this case object. If you haveSomeMethod(this IEnumerable<T> enumerable)
it will be available on allIEnumerable<T>
:s likeList<T>
.扩展方法:
http://msdn.microsoft.com/en-us/library/ bb383977.aspx
Extension method:
http://msdn.microsoft.com/en-us/library/bb383977.aspx