由于在方法内声明的变量仅在该方法中可用,并且在类中声明为private的变量仅在类中可用.this
关键词的目的是什么?为什么我要拥有以下内容:
private static class SomeClass : ISomeClass
{
private string variablename;
private void SomeMethod(string toConcat)
{
this.variablename = toConcat+toConcat;
return this.variablename;
}
}
Run Code Online (Sandbox Code Playgroud)
当这将完成同样的事情:
private static class SomeClass : ISomeClass
{
private string variablename;
private void SomeMethod(string toConcat)
{
variablename = toConcat+toConcat;
return variablename;
}
}
Run Code Online (Sandbox Code Playgroud)
练习我的打字技巧?
jal*_*alf 36
有几个案例很重要:
如果您有一个函数参数和一个具有相同名称的成员变量,您需要能够区分它们:
class Foo {
public Foo(int i) { this.i = i; }
private int i;
}
Run Code Online (Sandbox Code Playgroud)如果您确实需要引用当前对象,而不是其中一个成员.也许你需要将它传递给另一个函数:
class Foo {
public static DoSomething(Bar b) {...}
}
class Bar {
public Bar() { Foo.DoSomething(this); }
}
Run Code Online (Sandbox Code Playgroud)
当然,如果要返回对当前对象的引用,则同样适用
Tho*_*zer 28
在你的例子中,它纯粹是一种品味问题,但这是一个不是这样的情况:
private string SomeMethod(string variablename)
{
this.variablename = variablename;
return this.variablename;
}
Run Code Online (Sandbox Code Playgroud)
如果没有this
,代码将以不同的方式工作,将参数分配给自身.
Tar*_*don 15
在许多情况下这很有用.这是一个例子:
class Logger {
static public void OutputLog (object someObj) {
...
}
}
class SomeClass {
private void SomeMethod () {
Logger.OutputLog (this);
}
}
Run Code Online (Sandbox Code Playgroud)
这是另一个例子.假设我正在编写一个输出对象的Stream.Out方法,并返回对流本身的引用,如下所示:
class Stream {
public Stream Out (object obj) {
... code to output obj ...
return this;
}
}
Run Code Online (Sandbox Code Playgroud)
然后,可以在链接模式下使用此Out呼叫:
Stream S = new Stream (...);
S.Out (A). Out (B). Out (C);
Run Code Online (Sandbox Code Playgroud)
除了"现场消歧"和"通过当前意义的参考"答案(已经给出)之外,还有一个this
必要的附加场景; 在当前实例上调用扩展方法(我忽略了this
在声明扩展方法时的用法,因为这与问题的含义不完全相同):
class Foo
{
public void Bar()
{
this.ExtnMethod(); // fine
ExtnMethod(); // compile error
}
}
static class FooExt
{
public static void ExtnMethod(this Foo foo) {}
}
Run Code Online (Sandbox Code Playgroud)
公平地说,这不是常见的情况.更可能的是简单地使代码更具可读性,例如:
public bool Equals(Foo other) {
return other != null && this.X == other.X && this.Y == other.Y;
}
Run Code Online (Sandbox Code Playgroud)
在以上(或类似的Compare
,Clone
等等),而this.
我觉得有点......"不平衡".
归档时间: |
|
查看次数: |
4367 次 |
最近记录: |