简体   繁体   中英

F# static override

I have an abstract class, with an abstract member. I want to inherit this member to different classes and make the overrides of the member static.

Something like this:

[<AbstractClass>]
type Parent() = class
  abstract member Att : int
end;;
type Son() = class
  inherit Parent()
  static override Att = 10
end;;
type Daughter() = class
  inherit Parent()
  static override Att = 20
end;;

alternatively

[<AbstractClass>]
type Parent() = class
  static abstract member Att : int
end;;

or

[<AbstractClass>]
type Parent() = class
  abstract static member Att : int
end;;

Then all Sons would have Att=10 and all Daughters would have Att=20. This does not work.

Is there a way to make this work?

This is not possible from the definition of object model - static methods cannot be overriden in C# and any other object language as well.

This is mentioned eg here as well (for Java, but this is general to object-oriented programming):

Why cannot we override static method in the derived class

Overriding depends the an instance of a class. Polymorphism is that you can subclass a class and the objects implementing those subclasses will have different behaviors for those method defined in the superclass (and overridden in the subclasses). Static methods do not belong to an instance of a class so the concept is not applicable.

Specifically for abstract class, this won't make sense - you either call the method on the derived class (which means it doesn't need to be defined in the superclass), or on the superclass (which means it doesn't need to be abstract), or on an instance (which means it cannot be static).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM