How can a static class derive from an object?
我正在尝试通过静态类继承非静态类。
1 2 3 4 5 | public class foo { } public static class bar : foo { } |
我得到:
Static class cannot derive from type.
Static classes must derive from
object.
我怎样才能从物体中得到它?
该代码在C#中。
派生静态类没有任何价值。使用继承的原因有:
- 多态性
- 代码重用
显然,您无法通过静态类获得多态性,因为没有实例可以动态调度(换句话说,因为您没有Bar,所以您不可以将Bar传递给期望Foo的函数) 。
使用组合很容易解决代码重用:给Bar一个Foo的静态实例。
根据C#3.0规范的10.1.1.3节:
A static class may not include a
class-base specification (§10.1.4) and
cannot explicitly specify a base class
or a list of implemented interfaces. A
static class implicitly inherits from
typeobject .
换句话说,您无法执行此操作。
错误消息是伪造的。这不是说"一个"对象。讨论的是称为"对象"的内置类型,它是.NET中所有内容的基础。
应该说"静态类不能指定基本类型"。
摘自http://msdn.microsoft.com/zh-cn/library/79b3xss3(VS.80).aspx
The main features of a static class
are:They only contain static members.
They cannot be instantiated.
They are sealed.
They cannot contain Instance
Constructors (C# Programming Guide).
因此,通过将非静态成员引入静态类,从非静态类继承会违反此列表中静态类的第一个功能。
我不认为C#支持静态类的继承。
一种选择是改用单例模式
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | public class foo { } public class bar : foo { private bar instance; public bar GetInstance() { if(instance == null) instance = new bar(); return instance; } private bar(){} //make default constructor private to prevent instantiation } |
正如克里斯托弗指出的那样,假设我们可以从非静态类派生静态类。
例如:
1 2 3 4 5 6 | public class foo { public int myVar; } public static class bar : foo { } |
这里,bar类是从foo派生的,因此静态类Bar现在具有非静态成员myVar,并且根据c#Specification,静态类不能包含非静态成员!
如前所述,C#规范说这无法完成。您也不能使用静态类实现接口。最好的选择是从使用静态类更改为使用单例模式的类。您将只有一个实例(类似于静态类的工作方式),并且您将能够继承行为或实现接口。
您可以在此处,此处和此处阅读Singletons。
如在其他答案中所述,编译器消息令人困惑但正确。你可以写:
1 2 3 | static class A : object { } |
当然,明确声明此继承并不是真正有用,但是当您覆盖对象的虚拟成员时,继承本身在框架中实际上是有用的:
1 2 3 4 5 6 7 8 9 10 11 12 |
静态类不能作为其他类的基类,并且不能扩展。
静态类只能从"对象"类(.net基类)继承。
附加信息:.net中的所有类都继承自"对象"类,甚至任何静态类也都继承。
区别在于,即使静态类继承了"对象类",它也仅继承了"对象"类中的两个静态方法。
其他非静态类继承其他四个方法。
如果要阻止人们创建类的实例,只需添加一个私有的默认构造函数即可。
该错误信息是令人误解的。
bar无法从foo继承,因为foo可以实例化而bar无法。
所有类均隐式地从
不可以您必须创建一个普通类以从其他类派生。
并非所有类(包括静态类)都已经从对象派生了吗?如默认一样?
而且,就像它说的那样,"静态类不能从类型派生。",所以我认为您所做的事情是不可能的。无论如何,为什么要让静态类从类型派生?