为什么我不能覆盖静态方法? [英] Why I cant override static methods?

查看:90
本文介绍了为什么我不能覆盖静态方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么我无法覆盖c中的静态方法



我尝试过:



我试过Overriding Static Method但是我无法解释。

Why i can not override the static methods in c#

What I have tried:

I tried Overriding Static Method but i couldnt explain .

推荐答案

你不能覆盖静态方法,因为该方法与任何方法无关该类的特定实例,但在所有实例之间共享 - 因此它不能是虚拟的。



这意味着当您访问非静态方法时,你是通过一个实例来做的 - 就像你使用我的车,你的车,这辆车或那辆车从所有可能的相空间中指定一辆单独的车辆一样汽车。使用该实例,您可以提出问题或获取信息:

You can't override static methods because the method isn't related to any specific instance of the class, but shared between all instances - so it can't be virtual.

What that means is that when you access a non-static method, you do it via an instance - in much the same way that you use "my car", "your car", "this car", or "that car" to specify a single individual vehicle from the "phase space" of all possible cars. Using that instance, you can ask questions, or get information:
What colour is your car?
What fuel does this car use?

如果不指定特定的汽车,你不能问这些问题,因为汽车是什么颜色的?是一个荒谬的问题 - 它没有一个答案。但你可以说车有多少车轮?因为根据定义,所有汽车都有四个轮子 - 你不需要一个实例来提问。

在C#术语中,有多少轮子?是一个静态方法 - 您可以通过类名而不是通过实例访问它。这意味着你总是调用相同的方法 - 在派生类中调用同名的静态方法,你必须使用派生类名。

非静态方法是不同的:它们是通过可以是类或派生类的实际实例访问 - 当您尝试访问实例时,系统可以为实例的实际类选择方法的最高覆盖。

You can't ask those questions without specifying a particular car because "what colour is a car?" is a ridiculous question - it doesn't have a single answer. But you can say "how many wheels has a car?" because by definition, all cars have four wheels - you don't need an instance to ask the question.
In C# terms, "how many wheels?" is a static method - you access it via the class name rather than via an instance. Which means you always call the same method - to call a static method of the same name in a derived class you would have to use the derived class name instead.
Non-static methods are different: they are accessed via the actual instance which can be of a class or a derived class - and the system can select the "highest" override of a method for the actual class of the instance when you try to access it.


这篇关于为什么我不能覆盖静态方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆