简体   繁体   English

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

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

I have a helper class that is just a bunch of static methods and would like to subclass the helper class.我有一个助手 class ,它只是一堆 static 方法,并且想子类化助手 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).根据子类,某些行为是独一无二的,所以我想从基础 class 调用一个虚拟方法,但由于所有方法都是 static 我无法创建一个普通的虚拟方法(需要 ZA8CFDE6331BD59EB2AC96F8911CB6 引用才能访问虚拟方法)。

Is there any way around this?有没有办法解决? I guess I could use a singleton.. HelperClass.Instance.HelperMethod() isn't so much worse than HelperClass.HelperMethod().我想我可以使用 singleton .. HelperClass.Instance.HelperMethod() 并不比 HelperClass.HelperMethod() 差多少。 Brownie points for anyone that can point out some languages that support virtual static methods.任何可以指出一些支持虚拟 static 方法的语言的人都可以加分。

Edit: OK yeah I'm crazy.编辑:好的,是的,我疯了。 Google search results had me thinking I wasn't for a bit there.谷歌搜索结果让我觉得我不在那里。

Virtual static methods don't make sense. 虚拟静态方法没有意义。 If I call HelperClass.HelperMethod(); 如果我调用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? 当你有两个HelperClassHelperClass时,解决方案真的会崩溃 - 你会使用哪一个?

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. 选择在您的情况下更有意义的解决方案。

I don't think you are crazy. 我不认为你疯了。 You just want to use what is impossible currently in .NET. 您只想使用.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: 例如,我对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);
    }

Indeed, this can be done in Delphi. 实际上,这可以在Delphi中完成。 An example: 一个例子:

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. 我不再使用Delphi,但我记得能够使用元类特征在自定义设计器画布上轻松创建不同类型的控件:控件类,例如。 TButton, TTextBox etc. was a parameter, and I could call the appropriate constructor using the actual metaclass argument. TButton,TTextBox等是一个参数,我可以使用实际的元类参数调用适当的构造函数。

Kind of the poor man's factory pattern :) 那种穷人的工厂模式:)

You can achieve the same effect by just having a regular static method and then shadow it with the new keyword 只需使用常规静态方法然后使用new关键字对其进行遮蔽即可实现相同的效果

public class Base 
{
    //Other stuff

    public static void DoSomething()
    {
        Console.WriteLine("Base");
    }
}

public class SomeClass : Base
{
    public new static void DoSomething()
    {
        Console.WriteLine("SomeClass");
    }
}
public class SomeOtherClass : Base
{
}

Then you can call the methods like so 然后你可以调用这样的方法

Base.DoSomething(); //Base
SomeClass.DoSomething(); //SomeClass
SomeOtherClass.DoSomething(); //Base

I come from Delphi and this is a feature among many that I sorely miss in c#. 我来自Delphi,这是我在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. Delphi允许您创建类型化类型引用,并且您可以在需要父类类型的任何地方传递派生类的类型。 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: 我在这里混合语法非常糟糕,但在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 会产生:根源

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 type of 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语言。

You are not crazy. 你并不疯狂。 What you are referring to is called Late Static Binding; 你所指的叫做Late Static Binding; it's been recently added to PHP. 它最近被添加到PHP。 There's a great thread that describes it - here: When would you need to use late static binding? 有一个伟大的线程描述它 - 这里: 你什么时候需要使用后期静态绑定?

It is actually possible to combine virtual and static for a method or a member by using the keyword new instead 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 TyreCount value could have been set in the overridden GetTyreCount method, but this avoids duplicating the value. 显然, TyreCount值可以在重写的GetTyreCount方法中设置,但这可以避免重复该值。 It is possible to get the value both from the class and the class instance. 可以从类和类实例中获取值。

Now can someone find a really intelligent usage of that feature? 现在有人可以找到该功能的真正智能用途吗?

An override method provides a new implementation of a member that is inherited from a base class. override方法提供从基类继承的成员的新实现。 The method that is overridden by an override declaration is known as the overridden base method. 由覆盖声明覆盖的方法称为重写的基本方法。 The overridden base method must have the same signature as the override method. 重写的基本方法必须与覆盖方法具有相同的签名。 You cannot override a non-virtual or static method. 您不能覆盖非虚拟或静态方法。 The overridden base method must be virtual, abstract, or override. 重写的基本方法必须是虚拟,抽象或覆盖。

An override declaration cannot change the accessibility of the virtual method. 覆盖声明不能更改虚拟方法的可访问性。 Both the override method and the virtual method must have the same access level modifier. 覆盖方法和虚方法都必须具有相同的访问级别修饰符。

You cannot use the new, static, or virtual modifiers to modify an override method. 您不能使用new,static或virtual修饰符来修改覆盖方法。

An overriding property declaration must specify exactly the same access modifier, type, and name as the inherited property, and the overridden property must be virtual, abstract, or override. 覆盖属性声明必须指定与继承属性完全相同的访问修饰符,类型和名称,并且重写的属性必须是虚拟,抽象或覆盖。

I heard that Delphi suports something like this. 我听说Delphi支持这样的东西。 It seems it does it by making classes object instances of a metaclass. 它似乎是通过使类对象的元类实例来实现的。

I've not seen it work, so I'm not sure that it works, or what's the point for that. 我没有看到它的工作,所以我不确定它是否有效,或者它的重点是什么。

PS Please correct me if I'm wrong, since it's not my domain. 如果我错了,请纠正我,因为这不是我的域名。

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

There is a way to force an inheritance of "abstract static" methods from an abstract generic class. 有一种方法可以从抽象泛型类强制继承“抽象静态”方法。 See as follow : 见如下:

public abstract class Mother<T> where T : Mother<T>, new()
{
    public abstract void DoSomething();

    public static void Do()
    {
        (new T()).DoSomething();
    }

}

public class ChildA : Mother<ChildA>
{
    public override void DoSomething() { /* Your Code */ }
}

public class ChildB : Mother<ChildB>
{
    public override void DoSomething() { /* Your Code */ }
}

Example (using the previous Mother): 示例(使用以前的母亲):

public class ChildA : Mother<ChildA>
{
    public override void DoSomething() { Console.WriteLine("42"); }
}

public class ChildB : Mother<ChildB>
{
    public override void DoSomething() { Console.WriteLine("12"); }
}

public class Program
{
    static void Main()
    {
        ChildA.Do();  //42
        ChildB.Do();  //12
        Console.ReadKey();
    }
}

It's not that great since you can inherit from only one abstract class and it will ask you to be lenient with your new() implementation. 它不是那么好,因为你只能从一个抽象类继承,它会要求你对你的new()实现宽容。

More, I think it will be costly memory-wise depending on the size of your inherited classes. 更多,我认为根据你继承的类的大小,它将是昂贵的内存。 In case you have memory issue, you would have to set every properties/variables after your new in a public method which is an awful way to have default values. 如果您遇到内存问题,则必须在新方法之后在公共方法中设置每个属性/变量,这是一种非常有效的默认值。

Mart got it right with the 'new' keyword. Mart用'new'关键字做对了。 I actually got here because I needed this type of functionality and Mart's solution works fine. 我实际上到这里是因为我需要这种功能,Mart的解决方案运行正常。 In fact I took it one better and made my base class method abstract to force the programmer to supply this field. 事实上,我把它更好,并使我的基类方法抽象,以迫使程序员提供这个字段。

My scenario was as follows: 我的情况如下:

I have a base class HouseDeed. 我有一个基类HouseDeed。 Each House type is derived from HouseDeed must have a price. 每个House类型都源自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和实例新的SmallTowerDeed()访问房子的价格。价格和抽象,这种机制扼杀了程序员为每个新派生的房屋类型提供价格。

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)提供价格。

It is possible to simulate the functionality by using the new keyword in the derived class and throwing the NotSupportedException() in the base.可以通过在派生类中使用new关键字并在基类中抛出NotSupportedException()来模拟功能。

public class BaseClass{
    public static string GetString(){
        throw new NotSupportedException();   // This is not possible
    }
}

public class DerivedClassA : BaseClass {
    public static new string GetString(){
        return "This is derived class A";
    }
}

public class DerivedClassB : BaseClass {
    public static new string GetString(){
        return "This is derived class B";
    }
}

static public void Main(String[] args)
{
    Console.WriteLine(DerivedClassA.GetString());  // Prints "This is derived class A"
    Console.WriteLine(DerivedClassB.GetString());  // Prints "This is derived class B"
    Console.WriteLine(BaseClass.GetString());      // Throws NotSupportedException
}

Due to the fact that it is not possible to detect this condition at compile time and that IntelliSense won't suggest that such function should be implemented in the derived class, this is a potential headache.由于在编译时无法检测到这种情况,并且 IntelliSense 不会建议应在派生类中实现此类功能,因此这是一个潜在的麻烦。

One comment also suggested to use NotImplemetedException() .一条评论还建议使用NotImplemetedException() Microsoft's documentation indicates that neither of these exceptions should be handled so any of them should work. Microsoft 的文档表明不应处理这些异常中的任何一个,因此它们中的任何一个都应该起作用。

The differences between NotSupportedException and NotImplemetedException are commented in this blog . NotSupportedExceptionNotImplemetedException之间的区别在此博客中进行了评论。

You can use the new keyword 您可以使用new关键字

namespace AspDotNetStorefront
{
    // This Class is need to override StudioOnlineCommonHelper Methods in a branch
    public class StudioOnlineCommonHelper : StudioOnlineCore.StudioOnlineCommonHelper
    {
        //
        public static new void DoBusinessRulesChecks(Page page)
        {
            StudioOnlineCore.StudioOnlineCommonHelper.DoBusinessRulesChecks(page);
        }
    }
}

You will be able to soon, in C# 11!您很快就能在 C# 11 中!

From Tutorial: Explore C# 11 feature - static virtual members in interfaces :来自教程:探索 C# 11 功能 - static 接口中的虚拟成员

C# 11 and .NET 7 include static virtual members in interfaces . C# 11 和 .NET 7 包括接口中的 static 虚拟成员 This feature enables you to define interfaces that include overloaded operators or other static members.此功能使您能够定义包含重载运算符或其他 static 成员的接口。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 为什么不能在 C# 中声明静态结构,但它们可以有静态方法? - Why can't you declare a static struct in C#, but they can have static methods? 为什么我不能在 C# 中使用抽象静态方法? - Why can't I have abstract static methods in C#? 为什么不能将运算符或转换方法声明为虚拟的? C# - Why isn't It possible to declare operator or conversion methods virtual ? C# C#中的static变量有什么用? 什么时候使用它? 为什么我不能在方法内部声明 static 变量? - What is the use of static variable in C#? When to use it? Why can't I declare the static variable inside method? 有没有理由不能在C#方法中声明静态变量? - Is there reason why you can't declare a static variable within a C# method? C#虚拟(或抽象)静态方法 - C# virtual (or abstract) static methods 为什么 C# 不支持显式实现的虚拟方法? - Why doesn't C# support explicitly implemented virtual methods? C#不能声明具有相同参数的静态和非静态方法? - c# cannot declare static and non static methods with same parameters? 为什么 C# 不允许静态方法实现接口? - Why Doesn't C# Allow Static Methods to Implement an Interface? 为什么不支持C#静态类扩展方法? - Why aren't C# static class extension methods supported?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM