当类内声明了private 成员的时候,外面对这个是禁止访问的,之前学的C++是通过添加访问函数和更改函数来对其进行更改和访问,现在c#的set 和get 方法一个道理
set 方法里面有个value,就是对应的字段的值,比如说private string age ,对应的set 函数是 set string Age{age =value;} 当然我们也可以自定义Age函数体。
这样一来外界访问 age的时候 是通过
int x=对象名.Age;
的方式获取age的值
修改age是通过
对象名.Age=x;
的形式修改对象的age值
using System;
using System.Text;
namespace Excise1
{
public class Program
{
public class Student
{
private int age;
private string name;
private string id;
public int Age
{
get
{
return age;
}
set
{
age = value;
}
}
public string Name
{
get
{
return name;
}
set
{
name = value;
}
}
public string ID
{
get
{
return id;
}
set
{
id = value;
}
}
}
public static void Main(string[] args)
{
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
Student stu=new Student();
stu.Age = 18; //写stu对象的age
stu.ID = "45312311235x"; //写stu对象的id
stu.Name = "Michel"; //写stu对象的name
Console.WriteLine(stu.Age);//读取stu对象的age
Console.ReadKey();
}
}
}