Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I am trying to inherit a non-static class by a static class.

public class foo
{ }

public static class bar : foo
{ }

And I get:

Static class cannot derive from type. Static classes must derive from object.

How can I derive it from object?

The code is in C#.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
467 views
Welcome To Ask or Share your Answers For Others

1 Answer

There's no value in deriving static classes. The reasons to use inheritance are:

  • Polymorphism
  • Code reuse

You can't get polymorphism with static classes, obviously, because there is no instance to dynamically dispatch on (in other words, it's not like you can pass a Bar to a function expecting a Foo, since you don't have a Bar).

Code reuse is easily solved using composition: give Bar a static instance of Foo.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...