C# virtual static method

2019-01-22 06:09发布

Why is static virtual impossible? Is C# dependent or just don't have any sense in the OO world?

I know the concept has already been underlined but I did not find a simple answer to the previous question.

9条回答
霸刀☆藐视天下
2楼-- · 2019-01-22 07:02

In .NET, virtual method dispatch is (roughly) done by looking at the actual type of an object when the method is called at runtime, and finding the most overriding method from the class's vtable. When calling on a static class, there is no object instance to check, and so no vtable to do the lookup on.

查看更多
狗以群分
3楼-- · 2019-01-22 07:03

virtual means the method called will be chosen at run-time, depending on the dynamic type of the object. static means no object is necessary to call the method.

How do you propose to do both in the same method?

查看更多
三岁会撩人
4楼-- · 2019-01-22 07:09

The contradiction between "static" and "virtual" is only a c# problem. If "static" were replaced by "class level", like in many other languages, no one would be blindfolded.

Too bad the choice of words made c# crippled in this respect. It is still possible to call the Type.InvokeMember method to simulate a call to a class level, virtual method. You just have to pass the method name as a string. No compile time check, no strong typing and no control that subclasses implement the method.

Some Delphi beauty:

type
  TFormClass = class of TForm;
var
  formClass: TFormClass;
  myForm: TForm;
begin
  ...
  formClass = GetAnyFormClassYouWouldLike;
  myForm = formClass.Create(nil);
  myForm.Show;
end
查看更多
登录 后发表回答