简体   繁体   English

抽象类和静态类有什么区别?

[英]What's the difference between an abstract class and a static one?

Neither is instantiable.两者都不可实例化。 What are the differences, and in what situations might you use one or the other?有什么区别,在什么情况下您可以使用其中一种?

static indicates the class can only have static members and you cannot create an instance of it. static表示该类只能有静态成员,您不能创建它的实例。 This is used for stateless functionality (for example a type that just defines extension methods, or utility methods).这用于无状态功能(例如,仅定义扩展方法或实用程序方法的类型)。 You can also declare a member static on a non-static class.您还可以在非静态类上声明static成员。 This allows you to attach functionality to a type without having to instantiate it.这允许您将功能附加到类型而无需实例化它。

Here's more detail on using static members and classes .这里有更多关于使用静态成员和类的细节

abstract s define the basic structure and functionality shared by all derivative types, but cannot be used by themselves. abstract定义了所有派生类型共享的基本结构和功能,但不能单独使用。 Think of them as, I suppose, a blue print and a contract.我想,将它们视为蓝图和合同。 This is a core concept for OOP.这是 OOP 的核心概念。

Here's more detail on using abstracts . 这是有关使用摘要的更多详细信息

Here is a short summary:这是一个简短的总结:

  • A static class can only contain static members (it is just a container for methods that do not logically belong to an instance of any standard class)静态类只能包含static成员(它只是逻辑上不属于任何标准类实例的方法的容器)
  • An abstract class can contain all usual kinds of members (static, abstract and also instance)抽象类可以包含所有常见类型的成员(静态、抽象和实例)

The key difference is that you can inherit from an abstract class, but you cannot inherit from a static class.关键区别在于您可以从abstract类继承,但不能从static类继承。 Technically speaking, the .NET runtime doesn't have any notion of static classes, so the C# compiler compiles them as classes that are both abstract and sealed (meaning that you cannot inherit from them).从技术上讲,.NET 运行时没有任何static类的概念,因此 C# 编译器将它们编译为abstractsealed (意味着您不能从它们继承)。

So, static classes are abstract classes that are also sealed (although this is not the usual way to look at the problem if you are C# programmer) and contain only static members (which is enforced by the C# compiler).因此, static类是abstract类,也是sealed (尽管如果您是 C# 程序员,这不是查看问题的常用方法)并且仅包含static成员(由 C# 编译器强制执行)。

An abstract class is intended to be used as a base of a class inheritance hierarchy.抽象类旨在用作类继承层次结构的基础。 A static class cannot be the base of a class inheritance hierarchy.静态类不能作为类继承层次结构的基础。

A static class is intended for singleton state or stateless functionality.静态类用于单例状态或无状态功能。 An abstract class is not suitable for singleton functionality, because, even though it may contain static methods and fields as a static class does, it cannot forbid inheritance, so the singleton use may be defeated by subclasses.抽象类不适合单例功能,因为尽管它可能像静态类一样包含静态方法和字段,但它不能禁止继承,因此单例使用可能会被子类打败。 Or, at the very least, it would be confusing to other programmers, because its definition would communicate an intent that is different from its actual intended use.或者,至少,它会让其他程序员感到困惑,因为它的定义会传达与其实际预期用途不同的意图。

The superficial similarity between abstract and static classes is only in the fact that neither may be instantiated.抽象类和静态类之间表面上的相似之处仅在于两者都不能被实例化。 Beyond that, they are completely different animals with completely different use cases.除此之外,它们是完全不同的动物,具有完全不同的用例。

The CLR has no notion of static classes, it is specific to C#. CLR 没有静态类的概念,它特定于 C#。 The compiler implements it by slick use of CLR attributes for a class: it declares it abstract and sealed.编译器通过巧妙地使用类的 CLR 属性来实现它:它声明它是抽象的密封的。 That prevents any language from instantiating such a class.这可以防止任何语言实例化这样的类。 This is what it looks like when you run Ildasm:这是运行 Ildasm 时的样子:

.class public abstract auto ansi sealed beforefieldinit ConsoleApplication1.Test
       extends [mscorlib]System.Object
{
}

Making it sealed is very much the point of a static class, it is used as a container for static methods and fields.使其密封是静态类的重点,它用作静态方法和字段的容器。 Which makes them act like global variables and functions like you have in languages like C or Pascal.这使得它们像 C 或 Pascal 等语言中的全局变量和函数一样工作。

An abstract class is very much the opposite, it is designed to be derived from.抽象类恰恰相反,它被设计为派生自。 A abstract class that has all of its member abstract acts like an interface.具有其所有成员抽象的抽象类就像一个接口。 C# has a keyword for that, making static class and interface the exact opposites. C# 有一个关键字,使静态类和接口完全相反。

Abstract classes get instantiated indirectly via derived classes.抽象类通过派生类间接实例化。 They provide common behaviour and instance state, but signal that more is required and must be provided by derived concrete classes.它们提供通用行为和实例状态,但表明需要更多并且必须由派生的具体类提供。 For example, Transform might be an abstract class: it declares a common Apply(Shape) method, but no implementation of that method.例如, Transform可能是一个抽象类:它声明了一个通用的Apply(Shape)方法,但没有实现该方法。 Concrete derived classes like Rotation or Translation will implement that method, and those classes can be instantiated.RotationTranslation这样的具体派生类将实现该方法,并且这些类可以被实例化。

Static classes cannot be instantiated, and any state is at the class level rather than the instance level.静态类无法实例化,任何状态都在类级别而不是实例级别。 They are typically used to define utility methods where there is no state associated with the methods.它们通常用于定义没有与方法相关联的状态的实用方法。 Transform couldn't be a static class, because the concrete derived classes need per-instance state (eg Rotation needs a per-instance Angle , because different Rotation transforms could be by different angles). Transform不能是一个静态类,因为具体的派生类需要每个实例的状态(例如Rotation需要每个实例的Angle ,因为不同的Rotation变换可能是不同的角度)。

Abstract classes are intended to be used as base classes;抽象类旨在用作基类; they cannot have direct instances.他们不能有直接的实例。 Instead, you have to derive subclasses, which provide the what was (usually intentionally) left out in the abstract base class.相反,您必须派生子类,这些子类提供抽象基类中(通常有意)遗漏的内容。

Example: consider you have a complex application, where users may log-in to.示例:假设您有一个复杂的应用程序,用户可以在其中登录。 Various authentication mechanisms should be usable, say, LDAP, NTLM, you name it.应该可以使用各种身份验证机制,例如 LDAP、NTLM,等等。 One way to model a "user" or "principal" in such a context would be to collect, what is common across all those mechanisms, into an abstract base class, and leave "gaps" (abstract methods) where the actual implementations come into play:在这种上下文中对“用户”或“委托人”建模的一种方法是将所有这些机制中的共同点收集到一个抽象基类中,并在实际实现进入的地方留下“空白”(抽象方法)玩:

abstract class Authenticator {

   protected Dictionary<string,User> userCache;

   ...

   public User LoadUser(string name) {
        User user;
        if( userCache.TryGet(name, out user) ) return user;
        else {
            user = LoadFromStore(name);
            userCache.Add(name, user);
            return user;
        }
   }

   protected abstract User LoadFromStore(string name);
}

Here, caching of users is a common concern, modelled in the base case, whereas the actual retreival is left for a subclass to provide.在这里,用户的缓存是一个常见的问题,在基本情况下建模,而实际的检索则留给子类来提供。

Static class are a different matter alltogether.静态类完全是另一回事。 They are essentially a place to keep your utility functions:它们本质上是一个保存您的实用功能的地方:

static class StrUtil {

    public static string TrimWhitespace(string str) {
        ...
    }
}

Think of them as some kind of special namespace, which can only contain static members.将它们视为某种特殊的命名空间,只能包含静态成员。 Basically, a place to put functions.基本上,一个放置函数的地方。

Abstract Class (Base class): Enables other classes to inherit from this class ( one class acquires the properties (methods and fields) of another ) , but forbids to instantiate ie we cannot have objects of this class.抽象类(Base class):允许其他类继承这个类(一个类获取另一个类的属性(方法和字段) ),但是禁止实例化,即我们不能拥有这个类的对象。 http://csharp.net-tutorials.com/classes/abstract-classes http://csharp.net-tutorials.com/classes/abstract-classes

Static Class: This class cannot be instantiated .静态类:这个类不能被实例化 Also this class cannot be inherited .这个类也不能被继承 To access methods of this class, you can directly use classname.method.要访问该类的方法,您可以直接使用 classname.method。 https://social.technet.microsoft.com/wiki/contents/articles/21028.difference-between-static-class-sealed-class-and-abstract-class-in-c.aspx https://social.technet.microsoft.com/wiki/contents/articles/21028.difference-between-static-class-sealed-class-and-abstract-class-in-c.aspx

Abstract class main purpose is to define one or more abstract method(s).抽象类的主要目的是定义一个或多个抽象方法。 Any class extending Abstract class will implement the abstract method or else its also need to be declared as "Abstract".任何扩展抽象类的类都将实现抽象方法,否则它也需要声明为“抽象”。

But, its also possible to declare a class as "Abstract" without implementing any abstract method(s) in it.但是,也可以将类声明为“抽象”而不在其中实现任何抽象方法。 See the sample below.请参阅下面的示例。

public abstract class AbstractTest {
    public void abcd(){}

    public static void main(String[] args) {
        System.out.print("hi...");
    }
}

Only inner class can be declared as "Static", see the code below.只有内部类可以声明为“静态”,请参阅下面的代码。 Upper/encapsulating class can't be declared as "Static".上层/封装类不能声明为“静态”。 It can be accessed by using Upper/encapsulating class variable.Static-inner-classname ie same as any static method invocation using class name.它可以通过使用 Upper/encapsulating class variable.Static-inner-classname 来访问,即与使用类名的任何静态方法调用相同。

public class StaticTest {
    public static void main(String ag[]){
        System.out.println("hello...1");
        StaticTest.StaticTest2.meth2();
    }
    
    public static class StaticTest2 {
        public static void meth2(){
            System.out.print("hello...2");
        }
    }
}

Main difference between the two is extensibility.两者之间的主要区别是可扩展性。

CLR marks all 'static' classes as ' abstract & sealed ' behind the scene (ie, they cannot be inherited hence cannot be extended) and .NET Framework CLR loads them automatically when containing program or namespace is loaded. CLR在幕后将所有“静态”类标记为“抽象和密封”(即,它们不能被继承,因此不能扩展)并且 .NET Framework CLR 在加载包含程序或命名空间时自动加载它们。 This gives performance gain on runtime.这在运行时提供了性能增益。

Philosophy behind 'abstract' classes is capitalizing all common features of all extended classes in one place. “抽象”类背后的理念是将所有扩展类的所有共同特征都集中在一个地方。

Hope it helps.希望能帮助到你。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 抽象类静态方法和普通类静态方法有什么区别? - What is difference between abstract class static method and normal class static method? 静态结构方法和静态类方法有什么区别? - What's the difference between a static struct method and a static class method? 非静态方法和抽象类的静态方法有什么区别? - What is the difference between non-static method and static method of an abstract class? 抽象类的对象和抽象类的对象列表之间有什么区别? - What is the difference between object of an abstract class and list of objects of abstract class? 抽象类和只有受保护构造函数的类之间有什么区别? (。净) - What's the difference between an abstract class, and a class with only protected constructors? (.NET) 静态类和普通类有什么区别? - What is the difference between a static class and a normal class? 简单基类和抽象类有什么区别? - What is the difference between a simple base class and abstract class? 静态属性和单例之间有什么区别? - what's the difference between static property and singleton? MustInherit和抽象类之间的区别 - Difference between MustInherit and Abstract Class 静态函数之间有什么区别,一个属于静态类,另一个不属于静态类? - Is there any difference between static functions, one belongs to static class, another not?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM