了解类、嵌套类和成员的默认可见性

发布日期:2026-07-14 02:21:03   来源 : 杭州电子商务研究院    浏览量 :15
杭州电子商务研究院 发布日期:2026-07-14 02:21:03  
15

介绍

C# 是一种功能强大且简单的通用编程语言。它是一种面向对象的语言,这意味着对象是通过类创建的,并且在开发环境中具有各种范围或可见性。了解类、嵌套类和成员的默认可见性对于根据指定要求创建高效代码至关重要。

C# 中的类

类是 C# 的构建块。它用于形成对象,并在其上执行函数,这些函数构成了整个程序或软件的基础。类定义含义,即对象的类型和范围,并充当蓝图。类的实例是对象。与类相关的其他概念是其方法(执行特定功能的分组语句)和变量(根据其类型赋予存储区域的名称)。

如何定义类

首先提到关键字Class,然后是类的名称。类主体由花括号定义,如下例所示:

      <access specifier> class  ClassName {
    // Defining the class, members and variables
}
    

除了基本声明之外,还可以根据需要与类定义一起指定一些附加属性。

  • 修饰符:默认访问说明符是Internal,如果没有提及,方法访问就是Private
  • 类标识符:此处提及的是类类型的变量。按照惯例,标识符的首字母大写。
  • 基类/超类:如果一个类被继承(进一步详细说明),则可以提及其基类的名称,前面加上冒号
  • 接口:类可以实现多个接口,使用冒号:指定。一个类可以实现多个接口。
  • 主体:类主体在花括号{}内定义

为了熟悉这些概念,请参见下面的简单示例。

      <public> class  StudentInfo {
   // member variables
   <public> <int> Rollno;
   <public> <string> Name;
   ...
   <private> <int> primarykey;
   // member methods
   <public> <int> firstfunction(int,int) {
      // define method here
   }
   <private> <string> second function(parameter_list) {
      // define method here
   }
  }
    

下面的示例将在示例代码中演示我们迄今为止学到的所有方面。

现场演示

      using System;

namespace SimpleInterest {
   class Money {
      public double income;   // Income of First Person in family
      public double loan;  // Income of Second Person in family
      public double interest;   // The interest on a loan to be paid
   }
   class Expenses {
      static void Main(string[] args) {
         Money Money1 = new Money();   // Declare Money1 of type Money
         Money Money2 = new Money();   // Declare Money1 of type Money
         double expense = 0.0;    // Store the expenses here

         // Money 1 specification
         Money1.income = 5000.0;
         Money1.loan = 600.0;
         Money1.interest = 0.7;

         // Money 2 specification
         Money2.income = 10000.0;
         Money2.loan = 1200.0;
         Money2.interest = 0.85;
           
         // Expenses of first person 
         expense = Money1.income - Money1.loan * Money1.interest;
         Console.WriteLine("Expenses of First Person : {0}",  expense);

         // Expenses of second person
         expense = Money2.income - Money2.loan * Money2.interest;
         Console.WriteLine("Expenses of Second Person : {0}", expense);
         Console.ReadKey();
      }
   }
}
    

编译后我们得到最终的结果。

      Expenses of First Person : 4580
Expenses of Second Person : 8980
    

同样,您也可以使用实时演示功能来编写和练习您自己的代码。

请注意:

  • 点运算符可用于访问类变量,它充当类和成员名称之间的链接。
  • 数据类型将指定变量的类型。同时,返回类型表示方法返回的数据的数据类型(如果存在)。

类的成员函数

成员函数之所以被这样称呼,是因为它们是在类主体内定义的。因此,它们具有与类中定义的其他变量相同的原型。它们将对属于其自身类的对象进行操作,并可以访问该特定对象的类的所有成员。

成员变量本质上是给定对象的属性。它们是私有的,因此可以实现封装。在 C# 中,封装是指对象在用户不需要时隐藏其行为和相关数据的能力。通过此属性,可以将一组方法视为一个单元并作为一个单元执行。它们可以通过公共成员函数访问。

为了理解成员函数的概念及其范围,让我们看下面的例子。

      using System;

namespace MoneyApplication {
   class Money {
      private double income;   
      private double loan;  
      private double interest;   
      
      public void setIncome( double inc ) {
         income = inc;
      }
      public void setLoan( double lon ) {
         loan = lon;
      }
      public void setInterest( double itr ) {
         interest = itr;
      }
      public double getExpense() {
         return income * loan * interest;
      }
   }
   class Moneytester {
      static void Main(string[] args) {
         Money Money1 = new Money();   // Declare Money1 of type Money
         Money Money2 = new Money();
         double expense;
         
         // Declare Money2 of type Money
         // Money 1 specification
         Money1.setIncome(60.0);
         Money1.setLoan (57.0);
         Money1.setInterest(0.56);
         
         // Money 2 specification
         Money2.setIncome(20.0);
         Money2.setLoan(24.0);
         Money2. setInterest (0.09);
         
         // volume of Money 1
         expense = Money1.getExpense();
         Console.WriteLine("Expense of First Person ( Money1)  : {0}" ,expense);
         
         // volume of Money 2
         expense = Money2.getExpense();
         Console.WriteLine("Expense of Second Person ( Money2) : {0}", expense);
         
         Console.ReadKey();
      }
   }
}
    

构造函数

构造函数是一种特殊类型的类成员函数,执行该函数可创建该类的新对象。它在对象中实现该类的行为。

  • 它将始终具有与类相同的名称。
  • 它没有返回类型。
  • 默认情况下,构造函数没有参数。但如果需要,可以使用带参数的构造函数,在创建对象时为对象分配初始值。

析构函数

析构函数也是特定类的一种特殊类型的成员函数,当该类的对象超出范围时执行。

  • 与类具有相同的名称,但带有前缀波浪符号(~)
  • 没有返回值。
  • 不接受任何参数。
  • 对于在程序终止之前释放内存很有用。
  • 无法被重载或者继承。

对象

对象是 OOPS 和实现此实践的语言中最基本的单位。对象一旦创建,就会通过调用函数进行交互。它们可以被视为编程世界中的真实实体。

实例化类:通过创建对象来实例化类。给定的类可以有任意数量的对象。

初始化对象:new 运算符通过初始化类为新对象分配内存并返回对该内存位置的引用。

C# 编译器可以根据参数的数量及其类型区分构造函数。

嵌套类

在 C# 中,一个类可以与另一个类的定义一起定义。这些被称为嵌套类。它们允许用户将用于一个目的的类按逻辑或一起聚集在一起。这增强了封装属性,使代码更易读、更易于管理。

例如:

      using System;
// Outer class
public class OuterClass {
	// Method of outer class
    public void methodA(){
        Console.WriteLine("Outer class method called");
    }
    // Inner class
    public class InnerClass {
    	// Method of inner class
        public void methodB() {
            Console.WriteLine("Inner class Method called");
        }
    }
}
// Driver Class
public class Program {
    // Main method
    static public void Main(){
        // Create the instance of outer class
        OuterClass obj1 = new OuterClass();
        obj1.methodA();
        
        /* 
        This statement gives an error because you are not allowed 
        to access inner class methods with outer class objects.
        obj1. methodB();
        */
        
        // Creating an instance of inner class                              
        OuterClass.InnerClass obj2 = new OuterClass.InnerClass();            
        // Accessing the method of inner class
        obj2.methodB(); 
    } 
}
    

该代码的输出为:

      Outer class method called
Inner class Method called
    

笔记:

  • 嵌套类可以用任何访问修饰符来声明,即private、public、protected、internal、protected internal 或 private protected。

  • 外部类不能直接访问内部类成员,如上例所示。

  • 可以在外部类中创建内部类的对象。

  • 内部类可以访问外部类中声明的静态成员。方法如下:

    // Main Driver Class 
    public class DriverClass { 
        // Main method 
        static public void Main() {  
            // To access the static methodA of the inner class 
            OuterClass1.InnerClass2.methodA(); 
        } 
    } 
    

Some things to keep in mind with regard to nested classes:

    • The inner class can access any non-static member that has been declared in the outer class.

    • Scope of a nested class is limited by the scope of its (outer) enclosing class.

    • If nothing is specified, the nested class is private (default).

    • Any class can be inherited into another class in C# (including a nested class).

    • The user can inherit a nested class from outer class.

结论

本文介绍了如何在 C# 中定义类以及如何使用不同对象的范围来创建强大的代码。掌握了这些知识后,任何人都可以设置首选项、使用对象的权限和多态性等,从而减少代码行数并实现更好的性能优化。

快乐学习 C#!

以上内容来自杭州电子商务研究院推送
关注
关于我们
热门推荐
合作伙伴
免责声明:本站部分资讯来源于网络,如有侵权请及时联系客服,我们将尽快处理
Copyright © 2025-2027 ToB产业网址导航 公安备案 浙公网安备33010602013138号 浙ICP备16025413号-9
支持 反馈 关注 数据