有没有可以在静态类中实现的类?也就是说:
有没有一个类可以被既是sealed class又是static class的类继承?
意思:static class ABC : AClass {}
并且
sealed class ABC : AClass {}
static class ABC : Anyclass
我可能在某些方面错了吗?
有没有可以在静态类中实现的类?也就是说:
static class ABC : Anyclass
有没有一个类可以被既是sealed class又是static class的类继承?
意思:
static class ABC : AClass {}
并且
sealed class ABC : AClass {}
我可能在某些方面错了吗?
这可能对你有帮助:
+--------------+---+-------------------------+------------------+---------------------+
| Class Type | | Can inherit from others | Can be inherited | Can be instantiated |
|--------------|---|-------------------------+------------------+---------------------+
| normal | : | YES | YES | YES |
| abstract | : | YES | YES | NO |
| sealed | : | YES | NO | YES |
| static | : | NO | NO | NO |
+--------------+---+-------------------------+------------------+---------------------+
static class Foo : object { }
是有效的,但本质上等同于 static class Foo { }
。 - themefield简单来说
静态类
一个类可以被声明为静态,这意味着它仅包含静态成员。不可能使用new关键字创建静态类的实例。当程序或包含该类的命名空间被加载时,静态类会由.NET Framework公共语言运行时(CLR)自动加载。
密封类
密封类不能用作基类。密封类主要用于防止派生。因为它们永远不能用作基类,一些运行时优化可以使调用密封类成员略微更快。
您可以让一个sealed
类继承另一个类,但是您不能从sealed
类继承:
sealed class MySealedClass : BaseClass // is ok
class MyOtherClass : MySealedClass // won't compile
static
类不能继承其他类。 Sealed Class | Static Class
--------------------------|-------------------------
it can inherit From other | it cannot inherit From other
classes but cannot be | classes as well as cannot be
inherited | inherited
简单的回答是密封类不能用作基类。
我试图在下面的代码中向您展示密封类是一个派生类
public sealed class SealedClass : ClassBase
{
public override void Print()
{
base.Print();
}
}
另一个受限功能只能通过该实例访问(无法从中继承)。
class Program
{
static void Main(string[] args)
{
SealedClass objSeald = new SealedClass();
objSeald.Name = "Blah blah balh";
objSeald.Print();
}
}
public class BaseClassDemo
{
}
//Note
//A static class can be used as a convenient container for sets of
//methods that just operate on input parameters and do not have to
//get or set any internal instance fields.
//The advantage of using a static class is that the compiler can
//check to make sure that no instance members are accidentally
//added. The compiler will guarantee that instances of this class
//cannot be created.
//Static class 'static type' cannot derive from type 'type'. Static
//classes must derive from object.
public static class StaticClassDemo : BaseClassDemo //Error
public static class StaticClassDemo
{
//Static class must have static members
public static void Ram()
{
throw new NotImplementedException();
}
}
//Sealed class can inherit from the base class.
public sealed class SealedClassDemo : BaseClassDemo
{
}
//We can't derive from sealed class.
public class derivedClass:SealedClassDemo //Error
public partial class RandomClass2
{
//we can't create instance of static class.
StaticClassDemo demo = new StaticClassDemo() //Error
}
1 - 不,你不能实现一个静态类。
2 - 不,你不能从一个静态或密封类继承。