由于在方法内声明的变量仅在该方法内可用,而在类内声明为私有的变量仅在该类内可用。那么this
关键字的目的是什么?为什么我想要以下内容:
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;
}
}
练习我的打字技能吗?
this
关键字指的是类的实例,它会执行完全相同的操作。人们可能更喜欢使用this.variablename
来代替variablename
以提高可读性。 - Anthony Forloneyvoid
的方法中返回任何内容... - Sarah Vesselsthis
实际上是可以被赋值的,这非常酷。我本来想围绕这个建立一个大型答案,但问题是关于类的。 - Jeffrey L WhitledgeSystem.Object
。它实际上只继承了Object
中的两个static
方法。在这个问题中,ISomeClass
要么是一个接口(而静态类无法实现接口!),要么是一个与System.Object
不同的类。 - Jeppe Stig Nielsen