c#是我在高二的时候学习的一门语言,因为长时间没有去用这门语言,现在大一的我只能重新来学习c#
文章参照:http://www.runoob.com/csharp/csharp-encapsulation.html点击打开链接
C# 封装根据具体的需要,设置使用者的访问权限,并通过 访问修饰符 来实现。
一个 访问修饰符 定义了一个类成员的范围和可见性。C# 支持的访问修饰符如下所示:
- public:所有对象都可以访问;
- private:对象本身在对象内部可以访问;
- protected:只有该类对象及其子类对象可以访问
- internal:同一个程序集的对象可以访问;
- protected internal:访问限于当前程序集或派生自包含类的类型。
public修饰符
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace 封装
{
class res
{
public double width;
public double length;
public double getarea()
{
return width*length;
}
public void display()
{
Console.WriteLine("长度:{0}",length);
Console.WriteLine("宽度:{0}",width);
Console.WriteLine("面积:{0}",getarea());
}
}
class Program
{
static void Main(string[] args)
{
res r=new res ();
r.length = 5.3;
r.width = 4.2;
r.display();
Console.ReadKey();
}
}
}
如上所示,我定义了两个变量,都用到了public,所以在main函数里可以直接通过对res类创建的对象r来引用length,width
两个函数也用public修饰符来定义,所以也能被main函数来直接调用。
在其中我还发生了一点小插曲,就是在定义float类型的时候我以C语言的形式定义了没有在后面加f,我还研究了好一会。
private访问修饰符
Private 访问修饰符允许一个类将其成员变量和成员函数对其他的函数和对象进行隐藏。只有同一个类中的函数可以访问它的私有成员。即使是类的实例也不能访问它的私有成员。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace 封装
{
class res2
{
private double width;
private double length;
public void accept()
{
Console.WriteLine("请输入宽度");
width = Convert.ToDouble(Console.ReadLine());
Console.WriteLine("请输入长度");
length = Convert.ToDouble(Console.ReadLine());
}
private double getarea()
{
return length * width;
}
public void display()
{
Console.WriteLine("长度:{0}",length);
Console.WriteLine("宽度:{0}",width);
Console.WriteLine("面积:{0}",getarea());
}
}
class Program
{
static void Main(string[] args)
{
res2 r2 = new res2();
r2.accept();
r2.display();
Console.ReadKey();
}
}
}
运行结果
Internal 访问修饰符
Internal 访问说明符允许一个类将其成员变量和成员函数暴露给当前程序中的其他函数和对象。换句话说,带有 internal 访问修饰符的任何成员可以被定义在该成员所定义的应用程序内的任何类或方法访问。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace 封装
{
class res3
{
internal double width;
internal double length;
double getarea()
{
return width * length;
}
public void display()
{
Console.WriteLine("长度:{0}", length);
Console.WriteLine("宽度:{0}", width);
Console.WriteLine("面积:{0}", getarea());
}
}
class Program
{
static void Main(string[] args)
{
res3 r3 = new res3();
r3.length = 5.3;
r3.width = 4.2;
r3.display();
Console.ReadKey();
}
}
}
在上面的实例中,请注意成员函数 GetArea() 声明的时候不带有任何访问修饰符。如果没有指定访问修饰符,则使用类成员的默认访问修饰符,即为 private。
以上都是为了学习,对菜鸟教程都有所引用。