c#内部类的使用

时间:2022-11-16 21:36:05

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace 内部类Demo
{
class Program
{

static void Main(string[] args)
{
Student student = new Student("张三",20,"男");
student.ShowMsg();
}

public static void Test() {

Console.WriteLine("我是被内部类调用的外部静态方法");

}

public void Test2() {
Console.WriteLine("我是被内部内调用的外部非静态方法");
}

class Student {

private string name;

private int age;

private string sex;

public Student() { }
public Student(string name, int age, string sex) {

this.name = name;
this.age = age;
this.sex = sex;
}
public void ShowMsg() {

  Test();//访问外部内静态成员

new Program().Test2();//访问外部类非静态成员
Console.WriteLine("姓名:{0},年龄:{1},性别:{2}",name,age,sex);

}
}
}
}

(注意)c#内部类只能直接访问外部类的静态成员若要访问非静态成员则需要实例化外部类