在C#中构造函数中使用this关键字是否可行?(即,在构造函数中引用实例是否可行)
以下是一个简单的示例:
public class Test{
public Test()
{
Type type = this.GetType()
}
}
在C#中构造函数中使用this关键字是否可行?(即,在构造函数中引用实例是否可行)
以下是一个简单的示例:
public class Test{
public Test()
{
Type type = this.GetType()
}
}
是的,在构造函数中可以使用this
,但不能在字段初始化程序中使用。
因此,以下代码无效:
class Foo
{
private int _bar = this.GetBar();
int GetBar()
{
return 42;
}
}
但是这是允许的:
class Foo
{
private int _bar;
public Foo()
{
_bar = this.GetBar();
}
int GetBar()
{
return 42;
}
}
public class Test{
private string strName;
public Test(string strName)
{
this.strName = strName;
}
}
我认为在类的每个部分使用this
标识符是很好的选择...属性、方法、属性,因为它更具有暗示性,可以更快地了解你正在修改或使用什么,在复杂的类或大型类中,它可以帮助你更快地知道你正在使用什么,但正如我所说,这只是我的观点。
memberVariable
这种命名方式,会导致方法签名冲突,需要到处使用this
关键字。另外,我认为你可能想说的是"Explicit"而不是"Allusive"。 :) - Ed S.