为什么我不能有抽象静态方法在C#? [英] Why can't I have abstract static methods in C#?

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

问题描述

我一直使用公平位最近,我读到一篇有趣的情况下,我希望有一个有一个抽象的静态方法的抽象类。我读了关于这一主题的几个帖子,和排序它是有道理的,但有一个很好的解释清楚?

I've been working with providers a fair bit lately, and I came across an interesting situation where I wanted to have an abstract class that had an abstract static method. I read a few posts on the topic, and it sort of made sense, but is there a nice clear explanation?

推荐答案

静态方法没有的实例的正因为如此,他们只是没有提供对象引用。

Static methods are not instantiated as such, they're just available without an object reference.

一个调用静态方法是通过类名进行,而不是通过一个对象引用,而IL code调用它会通过定义它的类,名称叫抽象方法不一定是您使用的类的名称。

A call to a static method is done through the class name, not through an object reference, and the IL code to call it will call the abstract method through the name of the class that defined it, not necessarily the name of the class you used.

让我来告诉一个例子。

通过以​​下code:

With the following code:

public class A
{
public static void Test()
{
}
}

public class B : A
{
}

如果你调用B.Test,像这样的:

If you call B.Test, like this:

class Program
{
static void Main(string[] args)
{
B.Test();
}
}

然后在主方法中的实际code是如下:

Then the actual code inside the Main method is as follows:

.entrypoint
.maxstack 8
L0000: nop
L0001: call void ConsoleApplication1.A::Test()
L0006: nop
L0007: ret

正如你所看到的,调用,以A.Test,因为它是定义它的类,而不是B.Test,即使你可以c写这样的$ C $

As you can see, the call is made to A.Test, because it was the A class that defined it, and not to B.Test, even though you can write the code that way.

如果你有类类型的,像德尔福,在那里你可以做一个变量引用一个类型,而不是一个对象,你会对虚拟因而抽象静态方法的详细使用(也构造函数),但它们是不可用,因此静态调用都是非虚的.NET。

If you had class types, like in Delp where you can make a variable referring to a type and not an object, you would have more use for virtual and thus abstract static methods (and also constructors), but they aren't available and thus static calls are non-virtual in .NET.

我意识到,IL设计师可能允许code编译才能调用B.Test,并解决呼叫在运行时,但它仍然不会是虚拟的,因为你仍然需要编写一些类的名称出现。

I realize that the IL designers could allow the code to be compiled to call B.Test, and resolve the call at runtime, but it still wouldn't be virtual, as you would still have to write some kind of class name there.

虚拟方法,从而抽象的,只有有用的,当你使用它,在运行时,可以包含多个不同类型的对象变量,这样的话你要拨打正确的方法你在当前对象该变量。对于静态方法,你需要通过一个类名无论如何,所以打电话给确切的方法是在编译时间,因为它不能也不会改变。

Virtual methods, and thus abstract ones, are only useful when you're using a variable which, at runtime, can contain many different types of objects, and you thus want to call the right method for the current object you have in the variable. With static methods you need to go through a class name anyway, so the exact method to call is known at compile time because it can't and won't change.

因此​​,虚拟/抽象静态方法不是在.NET中可用。

Thus, virtual/abstract static methods are not available in .NET.

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

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