为什么在方法中使用 static 关键字
当我想到“静态”的东西时。我想到了一些不会改变的事情。这是否意味着非静态方法可以更改,但静态方法不能更改?他们的行为有什么不同吗?
When I think of something that's "static". I think of something that doesn't change. Does that mean non-static methods can change, but static methods don't? Do they behave differently?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
(假设您在这里谈论 C# - 它在不同语言中的含义略有不同,因此您最好用您要问的内容来标记您的问题。)
这里的“静态”一词用于表示“与类型相关而不是与类型的特定实例相关”。我相信它最初被使用是因为编译器可以静态确定成员的含义,而不是在执行时动态确定正在使用的成员(例如调用虚拟方法) )但现在已经失去了很多这种含义 :(
“static = 与类型本身相关,而不是实例”的含义在整个 C# 中是一致的,包括:
(Assuming you're talking about C# here - it means slightly different things in different languages, so you'd be wise to tag your question with exactly what you're asking about.)
The word "static" here is used to mean "related to a type rather than to a particular instance of a type". I believe it was originally used because the compiler could determine statically what a member meant, as opposed to the member in use being determined dynamically at execution time (e.g. invoking a virtual method) but it's lost a lot of that meaning now :(
The "static = related to the type itself, not an instance" meaning is consistent throughout C#, including:
静态方法不需要类实例。这是主要的区别。
静态
ClassName.MethodName();
非静态
var obj = new 类名();
obj.MethodName();
Static methods don't require a class instance. That is the main difference.
Static
ClassName.MethodName();
Not static
var obj = new ClassName();
obj.MethodName();
静态方法既不需要类的实例,也不能隐式访问此类实例的数据(或 this、self、Me 等)。
Static methods neither require an instance of the class nor can they implicitly access the data (or this, self, Me, etc.) of such an instance.
他们的行为并没有什么不同。正如之前所说,主要区别在于您不需要创建该方法的类的实例。变量也是如此。示例:
但请记住,静态方法无法访问该类中的非静态变量/方法。
They do not behave different. Like said before, the main difference is that you don't need to create an instance of the class of that method. Same goes for variables. Example:
But remember, a static method cannot access a non-static variable/method in that class.
它与要更改的方法无关。它与该方法正在操作的数据有关。如果它是静态方法,则它所操作的数据不依赖于类型的实例。因此我们不需要实例来调用它。
从方法操作的数据角度思考。数据是否依赖于实例。如果不将方法标记为静态。
Its not about the method that is going to be changed .Its about the data that the method is operating on. If its a static method the data it is operating on is not dependent on instance of a type.so we dont need an instance to call it.
Think in terms of data the method operates upon.Is the data dependent on an instance or not.if not mark method as static.