search
HomeBackend DevelopmentC#.Net TutorialC# Learning Diary 21----Encapsulation and access modifiers

Encapsulation:

is defined as "enclosing one or more projects in a physical or logical package." In object-oriented programming methodology, encapsulation is used to prevent access to implementation details. That is to say, the implementation details are wrapped up, so that the very complex logic can be conveniently used by others after being packaged. Others do not need to understand how it is implemented, and they can get the desired results by simply passing in the required parameters. Encapsulation is implemented using access modifiers. An access modifier defines the scope and visibility of a class member.

Access modifiers:

In Class Class Declaration and Definition, I briefly introduced the access modifiers. It is not very specific. Here we learn about the access modifiers in depth. ;

                                                                                                                                                                                                  that access modifier in C# have 5 types: public, private, protected, internal, protected internal; Its member variables and member functions are exposed to other functions and objects. Any public member can be accessed by outside classes. (Access to members is not restricted, subclasses are allowed, and objects are also allowed)

using System;  
using System.Collections.Generic;  
using System.Linq;  
using System.Text;  
  
namespace Test  
{  
    class student  
    {  
        public int Chinese=80;  
        public int Math=67;  
        public int English=45;  
         //定义一个方法  
        public int total()  
        {  
            int sum = 0;  
            sum = Chinese + Math + English;  
            return sum;  
        }  
    }  
    class teacher  
    {  
        static void Main(string[] args)  
        {  
            student stu = new student();  //实例化一个对象  
            Console.WriteLine("Chinese = {0}\nMath = {1}\nEnglish = {2}\nTotal = {3}",stu.Chinese,stu.Math,stu.English,stu.total());  
        }  
    }  
}

Output results:

In the above example, all in student The members are all public type access, so his instantiated object stu can access all members.

C# Learning Diary 21----Encapsulation and access modifiers

private modifier

The Private access modifier allows a class to hide its member variables and member methods from its objects. Only methods within the same class can access its private members. Even an instance of a class cannot access its private members (no access by its subclasses or objects is allowed).

We will use the above example:

using System;  
using System.Collections.Generic;  
using System.Linq;  
using System.Text;  
  
namespace Test  
{  
    class student  
    {  
        private int Chinese=80;  
        private int Math=67;  
        public int English=45;  
  
        private int total()  
        {  
            int sum = 0;  
            sum = Chinese + Math + English;  
            return sum;  
        }  
    }  
    class teacher  
    {  
        static void Main(string[] args)  
        {  
            student stu = new student();  
            int Chinese = stu.Chinese;     //出错了,不可访问(private)  
             
            int English = stu.English;   //可以访问 (public)  
  
            int total = stu.total();  // 不可访问 private 方法  
        }  
    }  
}

Since there are private access restrictions on the variables Chinese and Math method Total in the student class, they cannot be accessed through the object stu

protected modifier

The Protected access modifier allows a subclass to access the member variables and member functions of its base class. This helps implement inheritance. (Object access is not allowed, method access in the class is allowed, and subclass access is allowed)

using System;  
using System.Collections.Generic;  
using System.Linq;  
using System.Text;  
  
namespace Test  
{  
    class student  
    {  
        //定义protected 类型保护  
        protected int Chinese=80;  
        protected int Math=67;  
        protected int English=45;  
  
        protected int total()  
        {  
            int sum = 0;  
            sum = Chinese + Math + English;  
            return sum;  
        }  
    }  
    class teacher:student  //teacher 继承student类  
    {  
        static void Main(string[] args)  
        {  
            teacher teac = new teacher();   //创建子类 teacher 对象  
            //全部成功访问  
            int Chinese = teac.Chinese;      
             
            int English = teac.English;    
  
            int total = teac.total();  
              
        }  
    }  
}

internal modifier

The Internal access modifier allows a class to expose its member variables and member methods to Other methods and objects in the current assembly (current project). In other words, any member with the internal access modifier can be accessed by any class or method defined within the assembly (project) in which the member is defined.

To learn the internal modifier, we must first learn to use Vs2010 to create multiple projects and how to reference projects:

First create a project file: name it Test_internal

After clicking OK, find the solution manager:

C# Learning Diary 21----Encapsulation and access modifiers


Right-click the solution "Test_internal "(1 project) --->Add--->New project---->visual C#--->Console; In the name column we name it Class_internal OK; this way we create 2 projects (assemblies)

C# Learning Diary 21----Encapsulation and access modifiers


In fact, the name we entered above is the name of the namespace we defined. Open the code Class_internal The namespace is namespace Class_internal, and the namespace of Test_internal is namespace Test_internal. We use the using namespace in one project to reference the content of another project, but before that, we have to add the referenced project path in the "Reference" list. :

C# Learning Diary 21----Encapsulation and access modifiers Right-click "Reference"--->Add Reference--->Project. Find the project name to be referenced in the project name list. Here we select Class_internal. Click OK. Class_internal will appear in the reference list. The reference is successful.

We open the program in Class_internal .cs edit the following code

using System;  
using System.Collections.Generic;  
using System.Linq;  
using System.Text;  
  
namespace Class_internal  
{  
    public class student  
    {  //定义2个 internal 访问类型与一个public访问类型  
        internal int Chinese=80;  
        internal int Math=70;  
        public int English=56;  
      //定义一个internal 访问类型方法  
        internal int Total()  
        {  
            int sum = 0;  
            sum = Chinese + Math + English;  
            return sum;  
        }  
        static void Main(string[] args)  
        {   
          
        }  
    }  
     
}
C# Learning Diary 21----Encapsulation and access modifiers Then edit the following code in Test_internal:

using System;  
using System.Collections.Generic;  
using System.Linq;  
using System.Text;  
using Class_internal;  //引用命名空间  
  
namespace Test_internal  
{  
    class Program  
    {  
        static void Main(string[] args)  
        {  
            student stu = new student();  //实例化一个student类型  
            int Chinese = stu.Chinese;   //出错了,internal 保护类型无法在这个项目中访问  
            int Math = stu.Math;  //出错,同上  
            int English = stu.English;  // 成功访问public保护类型  
             
        }  
    }  
}

We use internal and public access types in Class_internal, and only public access is available in another project Test_internal type. This is internal

protected internal modifier

The Protected Internal access modifier allows a class to hide its member variables and member functions from other class objects and functions other than subclasses within the same application (project). (I don’t quite understand) In other words, it has the properties of protected and internal at the same time. Protected access is restricted to subclasses and can be accessed through inheritance in another assembly (project). Internal restricts access to other projects. The two Restrictions on overlay, protected types cannot be accessed in another project through inherited subclasses.

The above is the content of C# Learning Diary 21----Encapsulation and access modifiers. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!


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# .NET Development: A Beginner's Guide to Getting StartedC# .NET Development: A Beginner's Guide to Getting StartedApr 18, 2025 am 12:17 AM

To start C#.NET development, you need to: 1. Understand the basic knowledge of C# and the core concepts of the .NET framework; 2. Master the basic concepts of variables, data types, control structures, functions and classes; 3. Learn advanced features of C#, such as LINQ and asynchronous programming; 4. Be familiar with debugging techniques and performance optimization methods for common errors. With these steps, you can gradually penetrate the world of C#.NET and write efficient applications.

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.

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尊渡假赌尊渡假赌尊渡假赌
Will R.E.P.O. Have Crossplay?
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)