开发者

inherit a static class [duplicate]

This question already has answers here: Closed 12 years ago. 开发者_运维知识库

Possible Duplicate:

How can a static class derive from an object?

I have a static class and I want to inherit from another static class, but the compiler forbid to do so. "Static classes must derive from object"

I want to know why and is there any workaround?


Static means shared and it is not inheritable. There is no way you can do this.


It is not possible to inherit from a static class, they are sealed, and static method cannot be virtual.

I think you need to reconsider your design, you could consider using the singleton pattern instead of a static class, then you would be able to inherit with no problems.

Or just use a static member join the two classes:

static class A { static B b; }


You will not be able to accomplish this through inheritance. Try using the Composite Pattern.

In it, you have several objects that implement and interface and would be would be "composed" of a static class having it as its member. The benefit is that you could then add behaviors to each new class that implements your interface and the would be interchangeable at runtime.

EDIT:

    public class Foo
    {
        protected static class StaticClass
        {
            public static int Count { get; set; }
        }

        public virtual string GetBars()
        {
            return "I am Foo: " + StaticClass.Count++;
        }
    }

    public class FooToo:Foo
    {
        public override string GetBars()
        {
            return "I am Foo Too: " + StaticClass.Count++;
        }
    }

then...

Foo foo = new Foo();
Foo fooToo = new FooToo();

Console.WriteLine(foo.GetBars());
Console.WriteLine(fooToo.GetBars());
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜