为什么我不能声明 C# 方法虚拟和静态?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/248263/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-03 19:48:26  来源:igfitidea点击:

Why can't I declare C# methods virtual and static?

c#oop

提问by Luke

I have a helper class that is just a bunch of static methods and would like to subclass the helper class. Some behavior is unique depending on the subclass so I would like to call a virtual method from the base class, but since all the methods are static I can't create a plain virtual method (need object reference in order to access virtual method).

我有一个助手类,它只是一堆静态方法,并且想要子类化助手类。根据子类的不同,某些行为是独一无二的,因此我想从基类调用虚拟方法,但由于所有方法都是静态的,因此我无法创建普通的虚拟方法(需要对象引用才能访问虚拟方法)。

Is there any way around this? I guess I could use a singleton.. HelperClass.Instance.HelperMethod() isn't so much worse than HelperClass.HelperMethod(). Brownie points for anyone that can point out some languages that support virtual static methods.

有没有办法解决?我想我可以使用单例..HelperClass.Instance.HelperMethod() 并不比HelperClass.HelperMethod() 差多少。Brownie 指出任何可以指出一些支持虚拟静态方法的语言的人。

Edit:OK yeah I'm crazy. Google search results had me thinking I wasn't for a bit there.

编辑:好的,是的,我疯了。谷歌搜索结果让我觉得我不在那里。

采纳答案by Chris Marasti-Georg

Virtual static methods don't make sense. If I call HelperClass.HelperMethod();, why would I expect some random subclass' method to be called? The solution really breaks down when you have 2 subclasses of HelperClass- which one would you use?

虚拟静态方法没有意义。如果我调用HelperClass.HelperMethod();,为什么我会期望调用一些随机子类的方法?当您有 2 个子类时,解决方案真的会崩溃HelperClass——您会使用哪一个?

If you want to have overrideable static-type methods you should probably go with:

如果您想拥有可覆盖的静态类型方法,您可能应该使用:

  • A singleton, if you want the same subclass to be used globally.
  • A tradition class hierarchy, with a factory or dependency injection, if you want different behavior in different parts of your application.
  • 单例,如果您希望全局使用相同的子类。
  • 如果您希望在应用程序的不同部分具有不同的行为,则可以使用带有工厂或依赖项注入的传统类层次结构。

Choose whichever solution makes more sense in your situation.

选择在您的情况下更有意义的解决方案。

回答by Peter Parker

a static method exists outside of an instance of a class. It cannot use any non-static data.

静态方法存在于类的实例之外。它不能使用任何非静态数据。

a virtual method will be "overwritten" by an overloaded function depending of the typeof an instance.

根据实例的类型,虚方法将被重载的函数“覆盖” 。

so you have a clear contradiction between static and virtual.

所以你在静态和虚拟之间有明显的矛盾。

This is not a problem of support, It is a concept.

这不是支撑的问题,这是一个概念。

Update:I was proven wrong here(see comments):

更新:我在这里被证明是错误的(见评论):

So I doubt you will find any OOP-Language which will support virtual static methods.

所以我怀疑你会找到任何支持虚拟静态方法的 OOP 语言。

回答by rslite

I heard that Delphi suports something like this. It seems it does it by making classes object instances of a metaclass.

我听说 Delphi 支持这样的东西。似乎它是通过创建元类的类对象实例来实现的。

I've not seen it work, so I'm not sure that it works, or what's the point for that.

我还没有看到它起作用,所以我不确定它是否起作用,或者这有什么意义。

P.S. Please correct me if I'm wrong, since it's not my domain.

PS 如果我错了,请纠正我,因为这不是我的域。

回答by Alan

Indeed, this can be done in Delphi. An example:

事实上,这可以在 Delphi 中完成。一个例子:

type
  TForm1 = class(TForm)
    procedure FormShow(Sender: TObject);
  end;

  TTestClass = class
  public
    class procedure TestMethod(); virtual;
  end;

  TTestDerivedClass = class(TTestClass)
  public
    class procedure TestMethod(); override;
  end;

  TTestMetaClass = class of TTestClass;

var
  Form1: TForm1;

implementation

{$R *.dfm}

class procedure TTestClass.TestMethod();
begin
  Application.MessageBox('base', 'Message');
end;

class procedure TTestDerivedClass.TestMethod();
begin
  Application.MessageBox('descendant', 'Message');
end;


procedure TForm1.FormShow(Sender: TObject);
var
  sample: TTestMetaClass;
begin
  sample := TTestClass;
  sample.TestMethod;
  sample := TTestDerivedClass;
  sample.TestMethod;
end;

Quite interesting. I no longer use Delphi, but I recall being able to very easily create different types of controls on a custom designer canvas using the metaclass feature: the control class, eg. TButton, TTextBox etc. was a parameter, and I could call the appropriate constructor using the actual metaclass argument.

挺有意思。我不再使用 Delphi,但我记得能够使用元类功能在自定义设计器画布上非常轻松地创建不同类型的控件:控件类,例如。TButton、TTextBox 等是一个参数,我可以使用实际的元类参数调用适当的构造函数。

Kind of the poor man's factory pattern :)

那种穷人的工厂模式:)

回答by charles bretana

Because a virtual method uses the defined type of the instantiated object to determine which implementation to execute, (as opposed to the declared type of the reference variable)

因为虚方法使用实例化对象的定义类型来确定要执行的实现,(与引用变量的声明类型相反)

... and static, of course, is all about not caring if there's even an instantiated instance of the class at all...

......当然,静态就是根本不关心是否有类的实例化实例......

So these are incompatible.

所以这些是不相容的。

Bottom line, is if you want to change behavior based on which subclass an instance is, then the methods should have been virtual methods on the base class, not static methods.

底线是,如果您想根据实例是哪个子类来更改行为,那么这些方法应该是基类上的虚拟方法,而不是静态方法。

But, as you already have these static methods, and now need to override them, you can solve your problem by this: Add virtual instance methods to the base class that simply delegate to the static methods, and then override those virtual instance wrapper methods (not the static ones) in each derived subclass, as appropriate...

但是,由于您已经拥有这些静态方法,现在需要覆盖它们,您可以通过以下方式解决您的问题:将虚拟实例方法添加到简单委托给静态方法的基类,然后覆盖那些虚拟实例包装方法(不是静态的)在每个派生的子类中,视情况而定......

回答by Alex Weinstein

You are not crazy. What you are referring to is called Late Static Binding; it's been recently added to PHP. There's a great thread that describes it - here: When would you need to use late static binding?

你没有疯。您所指的称为后期静态绑定;它最近被添加到 PHP 中。有一个很好的线程描述它 - 在这里:您何时需要使用后期静态绑定?

回答by Mart

It is actually possible to combine virtual and static for a method or a member by using the keyword newinstead of virtual.

通过使用关键字new而不是 ,实际上可以为方法或成员组合虚拟和静态virtual

Here is an example:

下面是一个例子:

class Car
{
    public static int TyreCount = 4;
    public virtual int GetTyreCount() { return TyreCount; }
}
class Tricar : Car
{
    public static new int TyreCount = 3;
    public override int GetTyreCount() { return TyreCount; }
}

...

Car[] cc = new Car[] { new Tricar(), new Car() };
int t0 = cc[0].GetTyreCount(); // t0 == 3
int t1 = cc[1].GetTyreCount(); // t1 == 4

Obviously the TyreCountvalue could have been set in the overridden GetTyreCountmethod, but this avoids duplicating the value. It is possible to get the value both from the class and the class instance.

显然,该TyreCount值可以在被覆盖的GetTyreCount方法中设置,但这避免了重复该值。可以从类和类实例中获取值。

Now can someone find a really intelligent usage of that feature?

现在有人可以找到该功能的真正智能用法吗?

回答by SeeR

I don't think you are crazy. You just want to use what is impossible currently in .NET.

Your request for virtual static method would have so much sense if we are talking about generics. For example my future request for CLR designers is to allow me to write intereface like this:

我不认为你疯了。您只想使用 .NET 中目前无法实现的功能。

如果我们谈论的是泛型,那么您对虚拟静态方法的要求将非常有意义。例如,我未来对 CLR 设计师的要求是允许我编写这样的界面:

public interface ISumable<T>
{
  static T Add(T left, T right);
}

and use it like this:

并像这样使用它:

public T Aggregate<T>(T left, T right) where T : ISumable<T>
{
  return T.Add(left, right);
}

But it's impossible right now, so I'm doing it like this:

但现在不可能,所以我这样做:

    public static class Static<T> where T : new()
    {
      public static T Value = new T();
    }

    public interface ISumable<T>
    {
      T Add(T left, T right);
    }

    public T Aggregate<T>(T left, T right) where T : ISumable<T>, new()
    {
      return Static<T>.Value.Add(left, right);
    }

回答by Ken Revak

I come from Delphi and this is a feature among many that I sorely miss in c#. Delphi would allow you to create typed type references and you could pass the type of a derived class wherever the type of a parent class was needed. This treatment of types as objects had powerful utility. In particular allowing run time determination of meta data. I am horribly mixing syntax here but in c# it would look something like:

我来自 Delphi,这是我在 C# 中非常想念的许多功能中的一个。Delphi 允许您创建类型化类型引用,并且您可以在需要父类类型的任何地方传递派生类的类型。这种将类型作为对象的处理具有强大的实用性。特别是允许元数据的运行时确定。我在这里混合了可怕的语法,但在 C# 中它看起来像:

    class Root {
       public static virtual string TestMethod() {return "Root"; }
    }
    TRootClass = class of TRoot; // Here is the typed type declaration

    class Derived : Root {
       public static overide string TestMethod(){ return "derived"; }
    }

   class Test {
        public static string Run(){
           TRootClass rc;
           rc = Root;
           Test(rc);
           rc = Derived();
           Test(rc);
        }
        public static Test(TRootClass AClass){
           string str = AClass.TestMethod();
           Console.WriteLine(str);
        }
    } 

would produce: Root derived

将产生:根派生

回答by Level 42

Mart got it right with the 'new' keyword. I actually got here because I needed this type of functionality and Mart's solution works fine. In fact I took it one better and made my base class method abstract to force the programmer to supply this field.

Mart 用“new”关键字做对了。我来到这里是因为我需要这种类型的功能,而 Mart 的解决方案运行良好。事实上,我把它做得更好,并让我的基类方法抽象,以强制程序员提供这个字段。

My scenario was as follows:

我的情况如下:

I have a base class HouseDeed. Each House type is derived from HouseDeed must have a price.

我有一个基类 HouseDeed。每种房屋类型都源自 HouseDeed 必须有一个价格。

Here is the partial base HouseDeed class:

这是部分基础的 HouseDeed 类:

public abstract class HouseDeed : Item
{
    public static int m_price = 0;
    public abstract int Price { get; }
    /* more impl here */
}

Now lets look at two derived house types:

现在让我们看看两种派生的房屋类型:

public class FieldStoneHouseDeed : HouseDeed
{
    public static new int m_price = 43800;
    public override int Price { get { return m_price; } }
    /* more impl here */
}

and...

和...

public class SmallTowerDeed : HouseDeed
{
    public static new int m_price = 88500;
    public override int Price { get { return m_price; } }
    /* more impl here */
}

As you can see I can access the price of the house via type SmallTowerDeed.m_price, and the instance new SmallTowerDeed().Price And being abstract, this mechanism nags the programmer into supplying a price for each new derived house type.

正如您所看到的,我可以通过类型 SmallTowerDeed.m_price 和实例 new SmallTowerDeed().Price 访问房屋的价格,而且是抽象的,这种机制促使程序员为每个新的派生房屋类型提供价格。

Someone pointed how 'static virtual' and 'virtual' are conceptually at odds with one another. I disagree. In this example, the static methods do not need access to the instance data, and so the requirements that (1) the price be available via the TYPE alone, and that (2) a price be supplied are met.

有人指出“静态虚拟”和“虚拟”在概念上是如何相互矛盾的。我不同意。在此示例中,静态方法不需要访问实例数据,因此满足以下要求:(1) 仅通过 TYPE 可获得价格,以及 (2) 提供价格。