search
HomeBackend DevelopmentC#.Net TutorialC# basic knowledge compilation: C# classes and structures (3)

1. What are the functional features of static classes and static members? Implement code?
Static classes and static members refer to classes or members defined using the static keyword. All members of a static class must be static members, otherwise an error will be reported. One of the characteristics of static classes and members is that they are unique. If it is a static class, it cannot be instantiated, and there is only one loaded in the memory; if it is a static variable or method, if this class can be instantiated, no matter how many times it is instantiated, there will always be only one static variable or method.
are as follows:
(1), static members

    public class StatTicMember
    {
        public static string testA = string.Empty;
    }
    
    class Program
    {
        static void Main(string[] args)
        {
            //StaticConstruct strc = new StaticConstruct();

            //StaticConstruct strcValue = new StaticConstruct(string.Empty);

            StatTicMember sMember1 = new StatTicMember();

            StatTicMember.testA = @"静态成员";

            Console.WriteLine(StatTicMember.testA);

            StatTicMember sMember2 = new StatTicMember();

            Console.WriteLine(StatTicMember.testA);

            Console.ReadLine();
        }
    }

Result:

Characteristics of static members:
a. Must be referenced through the class name, Cannot be referenced by objects of the class;
b. No matter how many times the class is instantiated, there is only the same area in the memory;
c. If variables or methods outside the method are referenced in a static method, they must also be Static, such as

    public class StatTicMember
    {
        public static string testA = string.Empty;

        public  string testB = string.Empty;

        public static void Method()
        {
            testA = @"my";//正确

            //testB = @"my";//错误
        }
    }

(2), static class

  public static class StaticClass
    {
        public static string testA = string.Empty;

        public static void StaticMethod()
        {
            Console.WriteLine(@"静态方法");
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            StaticClass.testA = @"静态类";

            Console.WriteLine(StaticClass.testA);

            StaticClass.StaticMethod();

            Console.ReadLine();
        }
    }

Result:

Static class characteristics:
a. Members must also be static;
b. It cannot be instantiated. Use the class name directly to reference internal members;
c. It is a sealed class; (Note: Sealed class means that this class cannot be used as a base class, and cannot be an abstract class, that is, it cannot Derived. )
d. Cannot contain constructors.
When using static classes and members, static classes cannot be used extensively, because once it is loaded, there is an area in the memory, and it is there whether you use it or not. takes up memory. It can be used in the following situations:
a. Global variable, a variable used in the entire project, and the value cannot be changed easily, even if all modules are changed, they must respond.
b. Methods that do not operate on instance data and are not associated with specific classes in the code, such as some methods in the Math class.
2. Sealed functional features? Implement code? Why use sealed classes?
A sealed class refers to a class modified with the sealed keyword. Its purpose is to prevent derivation, that is, this class cannot be inherited.
Features:
Cannot be used as a base class, cannot be abstracted, and the call to a sealed class is faster.

    public sealed class SealedClass
    {
        public  string testA = string.Empty;
    }

3. What is an abstract class? Features? Implement code? What is the difference between interface and abstract class?
Abstract class refers to a class modified with the abstract keyword. Its function is to derive multiple classes and share the public methods and properties of the base class.

   public abstract class AbstractClass
    {
        public abstract void CommonMethod();
    }

    public class ChildClass1 : AbstractClass
    {

        public override void CommonMethod()
        {
            Console.WriteLine(@"实现公用方法1");
        }
    }

    public class ChildClass2 : AbstractClass
    {

        public override void CommonMethod()
        {
            Console.WriteLine(@"实现公用方法2");
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            ChildClass1 chc1 = new ChildClass1();

            chc1.CommonMethod();

            ChildClass2 chc2 = new ChildClass2();

            chc2.CommonMethod();

            Console.ReadLine();
        }
    }

Result:


The difference between abstract class and interface:
a. A class is an abstraction of an object. Abstract classes can be understood as treating classes as Objects are abstracted into classes called abstract classes. The interface is just a specification or regulation of behavior. Microsoft's custom interface is always followed by an able field, which proves that it expresses a class "I can do...". Abstract classes are more defined in a series of closely related Between classes, most interfaces are loosely related but all implement a certain function;
b. The interface basically does not have any specific characteristics of inheritance, it only promises methods that can be called;
c , A class can implement several interfaces at a time, but can only extend one parent class;
d. Interfaces can be used to support callbacks, but inheritance does not have this feature;
e. Abstract classes cannot be sealed;
                                                                              ##                                               # Similar to classes, an abstract class must also provide its own implementations for all members of the interfaces listed in the class's base class list. However, abstract classes are allowed to map interface methods to abstract methods;
h. Abstract classes implement a principle in oop, which separates the mutable and the immutable. Abstract classes and interfaces are defined as immutable, and the mutable ones are left to subclasses for implementation;
i. A good interface definition should have specific functionality, not multi-function, otherwise the interface will become pollute. If a class only implements one function of the interface and has to implement other methods in the interface, it is called interface pollution;
j. If the abstract class implements the interface, the methods in the interface can be mapped to the abstract class As an abstract method in the interface, it does not need to be implemented, but the methods in the interface are implemented in the subclass of the abstract class.

The above is the above content. For more related content, please pay attention to the PHP Chinese website (m.sbmmt.com)! For more related content, please pay attention to the PHP Chinese website (m.sbmmt.com)!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
C# and .NET: Understanding the Relationship Between the TwoC# and .NET: Understanding the Relationship Between the TwoApr 17, 2025 am 12:07 AM

The relationship between C# and .NET is inseparable, but they are not the same thing. C# is a programming language, while .NET is a development platform. C# is used to write code, compile into .NET's intermediate language (IL), and executed by the .NET runtime (CLR).

The Continued Relevance of C# .NET: A Look at Current UsageThe Continued Relevance of C# .NET: A Look at Current UsageApr 16, 2025 am 12:07 AM

C#.NET is still important because it provides powerful tools and libraries that support multiple application development. 1) C# combines .NET framework to make development efficient and convenient. 2) C#'s type safety and garbage collection mechanism enhance its advantages. 3) .NET provides a cross-platform running environment and rich APIs, improving development flexibility.

From Web to Desktop: The Versatility of C# .NETFrom Web to Desktop: The Versatility of C# .NETApr 15, 2025 am 12:07 AM

C#.NETisversatileforbothwebanddesktopdevelopment.1)Forweb,useASP.NETfordynamicapplications.2)Fordesktop,employWindowsFormsorWPFforrichinterfaces.3)UseXamarinforcross-platformdevelopment,enablingcodesharingacrossWindows,macOS,Linux,andmobiledevices.

C# .NET and the Future: Adapting to New TechnologiesC# .NET and the Future: Adapting to New TechnologiesApr 14, 2025 am 12:06 AM

C# and .NET adapt to the needs of emerging technologies through continuous updates and optimizations. 1) C# 9.0 and .NET5 introduce record type and performance optimization. 2) .NETCore enhances cloud native and containerized support. 3) ASP.NETCore integrates with modern web technologies. 4) ML.NET supports machine learning and artificial intelligence. 5) Asynchronous programming and best practices improve performance.

Is C# .NET Right for You? Evaluating its ApplicabilityIs C# .NET Right for You? Evaluating its ApplicabilityApr 13, 2025 am 12:03 AM

C#.NETissuitableforenterprise-levelapplicationswithintheMicrosoftecosystemduetoitsstrongtyping,richlibraries,androbustperformance.However,itmaynotbeidealforcross-platformdevelopmentorwhenrawspeediscritical,wherelanguageslikeRustorGomightbepreferable.

C# Code within .NET: Exploring the Programming ProcessC# Code within .NET: Exploring the Programming ProcessApr 12, 2025 am 12:02 AM

The programming process of C# in .NET includes the following steps: 1) writing C# code, 2) compiling into an intermediate language (IL), and 3) executing by the .NET runtime (CLR). The advantages of C# in .NET are its modern syntax, powerful type system and tight integration with the .NET framework, suitable for various development scenarios from desktop applications to web services.

C# .NET: Exploring Core Concepts and Programming FundamentalsC# .NET: Exploring Core Concepts and Programming FundamentalsApr 10, 2025 am 09:32 AM

C# is a modern, object-oriented programming language developed by Microsoft and as part of the .NET framework. 1.C# supports object-oriented programming (OOP), including encapsulation, inheritance and polymorphism. 2. Asynchronous programming in C# is implemented through async and await keywords to improve application responsiveness. 3. Use LINQ to process data collections concisely. 4. Common errors include null reference exceptions and index out-of-range exceptions. Debugging skills include using a debugger and exception handling. 5. Performance optimization includes using StringBuilder and avoiding unnecessary packing and unboxing.

Testing C# .NET Applications: Unit, Integration, and End-to-End TestingTesting C# .NET Applications: Unit, Integration, and End-to-End TestingApr 09, 2025 am 12:04 AM

Testing strategies for C#.NET applications include unit testing, integration testing, and end-to-end testing. 1. Unit testing ensures that the minimum unit of the code works independently, using the MSTest, NUnit or xUnit framework. 2. Integrated tests verify the functions of multiple units combined, commonly used simulated data and external services. 3. End-to-end testing simulates the user's complete operation process, and Selenium is usually used for automated testing.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment