1.概念
C#是面向对象的一门语言,面向对象的语言有三大特性:封装、继承、多态。而封装可以实现一个自定义的类,从而定义新的对象
封装是将一个或多个项目集合在一个单元中,这个单元称之为类。这样可以防止对实现细节的访问
C#封装可以根据需要通过修饰符实现类成员的范围和可见性。访问修饰符有:
public:公共的,任何地方都可以访问,但是需要引用命名空间
private:私有的,类的内部才可以访问
internal:内部的,默认的,程序集中可以访问,程序集就是命名空间
protected:被保护的,类的内部和类的父类和子类中可以访问
Protected internal :protected和internal的并集,符合任意一条都可以访问
2.示例代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace fengzhuang
{
class Student
{
private string _code; //成员变量
private string _sex;
private int _age;
public string Code //进行封装的时候要用public,保证类外可以使用
{
get
{
return _code; //成员属性
} //属性一般用小写字母表示,但是封装的时候首字符要大写
set
{
_code = value;
}
}
public string Sex
{
get
{
return _sex; //成员属性
}
set
{
_sex = value;
}
}
public int Age
{
get
{
return _age; //成员属性
}
set {
_age = value;
}
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace fengzhuang
{
class Program
{
static void Main(string[] args)
{
Student XiaoMing = new Student();
XiaoMing.Code = "001";
XiaoMing.Sex = "男";
XiaoMing.Age = 18;
Console.WriteLine(XiaoMing.Code);
Console.WriteLine(XiaoMing.Sex);
Console.WriteLine(XiaoMing.Age);
}
}
}
3.效果图