为什么我无法使用关键字“this”当引用静态方法中的字段? [英] Why can't I use the keyword "this" when referring to fields in static methods?
问题描述
public class Date
{
static int month;
public static void setMonth(int x)
{
this.month = x; //compiler error
}
public static int getMonth()
{
return month; //compiles just fine, no error
}
}
当编译时,我收到错误:非静态变量这不能从静态上下文引用。
但是,如果我删除this。没有错误。
我不明白为什么当我使用关键字static清楚地声明它是一个非静态变量。
When compiling, I receive the error: non-static variable this cannot be referenced from a static context. However, if I remove "this." there is no error. I don't understand why it's saying month is a non-static variable when I clearly declared it using the keyword static.
推荐答案
你不能在静态上下文中使用 this
。这是通过设计 - 这
指的是对象而不是类。如果您在方法参数和字段之间可能发生名称冲突,您可以改用类名称:
You simply can't use this
in a static context. That is by design - this
refers to the object not the class. If you are having problems with possible name clashes between method parameters and fields you can use the class name instead:
public static void setMonth(int month)
{
Date.month = month;
}
另一方面,您可以考虑您的设计并重新思考使用整个类作为一个单例对象。
On the other hand you could think about your design and rethink the decision to use the whole class as one singleton object.
这篇关于为什么我无法使用关键字“this”当引用静态方法中的字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!