什么是“本”关键字在C#中的目的 [英] What is the purpose of 'this' keyword in C#
问题描述
由于方法内声明的变量只在该方法是可用的,和变量声明的类中的私有只提供一类中。什么是这个
键字的目的是什么?我为什么要具备以下条件:
Since variables declared inside a method are available only within that method, and variables declared private within a class are only available within a class. What is the purpose of the this
key word? Why would I want to have the following:
private static class SomeClass : ISomeClass
{
private string variablename;
private void SomeMethod(string toConcat)
{
this.variablename = toConcat+toConcat;
return this.variablename;
}
}
在此会做同样的事情:
private static class SomeClass : ISomeClass
{
private string variablename;
private void SomeMethod(string toConcat)
{
variablename = toConcat+toConcat;
return variablename;
}
}
练习我的打字技能?
to practice my typing skills?
推荐答案
有一对夫妇的情况下,如果它的问题:
There are a couple of cases where it matters:
-
如果你有一个函数参数,并具有相同名称的成员变量,你必须能够区分它们:
If you have a function parameter and a member variable with the same names, you need to be able to distinguish them:
class Foo {
public Foo(int i) { this.i = i; }
private int i;
}
如果你确实需要引用的当前对象的,而不是它的成员之一。也许你需要将它传递给另外一个函数:
If you actually need to reference the current object, rather than one of its members. Perhaps you need to pass it to another function:
class Foo {
public static DoSomething(Bar b) {...}
}
class Bar {
public Bar() { Foo.DoSomething(this); }
}
当然,如果你想同样也适用于的收益当前对象的引用
这篇关于什么是“本”关键字在C#中的目的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!