问题描述
有人告诉我static
方法是隐式final
的,因此不能被覆盖.真的吗?
I was told that static
methods are implicitly final
and therefore can't be overridden. Is that true?
-
有人可以举一个更好的重写静态方法的例子吗?
Can someone give a better example of overriding a static method?
如果静态方法只是类方法,那么拥有它们的真正用途是什么?
If static methods are just class methods, what is the real use of having them?
推荐答案
(1)静态方法不能被覆盖,但是可以使用'new'关键字将其隐藏.大多数情况下,覆盖方法意味着您引用基本类型并希望调用派生方法.由于static是该类型的一部分,因此不需要进行无意义的vtable查找.
(1) Static methods cannot be overridden, they can however be hidden using the 'new' keyword. Mostly overriding methods means you reference a base type and want to call a derived method. Since static's are part of the type and aren't subject to vtable lookups that doesn't make sense.
例如静力学不能做到:
public class Foo {
public virtual void Bar() { ... }
}
public class Bar : Foo {
public override void Bar() { ... }
}
// use:
Foo foo = new Bar(); // make an instance
foo.Bar(); // calls Bar::Bar
由于静态方法不适用于实例,因此您始终必须明确指定Foo.Bar或Bar.Bar.因此,这里的覆盖没有任何意义(尝试用代码表达……).
Because statics don't work on instances, you always specify Foo.Bar or Bar.Bar explicitly. So overriding has no meaning here (try expressing it in code...).
(2)静态方法有不同的用法.例如,在Singleton模式中使用它来获取类型的单个实例.另一个示例是"static void Main",它是程序中的主要访问点.
(2) There are different usages for static methods. For example, it's being used in the Singleton pattern to get a single instance of a type. Another example is 'static void Main', which is the main access point in your program.
基本上,您可以在不需要或无法创建对象实例之前使用它们.例如,当静态方法创建对象时.
Basically you use them whenever you don't want or cannot create an object instance before using it. For example, when the static method creates the object.
[更新]
一个简单的隐藏示例:
public class StaticTest
{
public static void Foo() { Console.WriteLine("Foo 1"); }
public static void Bar() { Console.WriteLine("Bar 1"); }
}
public class StaticTest2 : StaticTest
{
public new static void Foo() { Console.WriteLine("Foo 2"); }
public static void Some() { Foo(); Bar(); } // Will print Foo 2, Bar 1
}
public class TestStatic
{
static void Main(string[] args)
{
StaticTest2.Foo();
StaticTest2.Some();
StaticTest.Foo();
Console.ReadLine();
}
}
请注意,如果您将类设为static
,则无法执行此操作.静态类必须从object
派生.
Note that if you make the classes static
, you cannot do this. Static classes have to derive from object
.
此继承与继承之间的主要区别在于,编译器可以在编译时确定使用static时要调用哪种方法.如果有对象实例,则需要在运行时执行此操作(称为vtable查找).
The main difference between this and inheritance is that the compiler can determine at compile-time which method to call when using static. If you have instances of objects, you need to do this at runtime (which is called a vtable lookup).
这篇关于可以在C#中重写静态方法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!