字段加GetSet方法可以加限制
字段加GetSet方法可以加限制
访问和设置
C# 的set和get方法基本相同。
class Vector3
{
private double x;
private double y;
private double z;
public double Length()
{
double res=Math.Sqrt(x * x + y * y + z * z);
Console.WriteLine("res="+res);
return res;
}
public void SetX(double temp)
{
if (temp<0)
{
return;
}
x = temp;
}
public void SetY(double temp)
{
if (temp < 0)
{
return;
}
y = temp;
}
public void SetZ(double temp)
{
if (temp < 0)
{
return;
}
z = temp;
}
public double GetX()
{
return x;
}
public double GetY()
{
return y;
}
public double GetZ()
{
return z;
}
}class Student
{
public string name;
public int age;
public string address;
public string createTime;
public void Show()
{
Console.WriteLine("名字:" + name);
Console.WriteLine("地址:" + address);
Console.WriteLine("年龄:" + age);
Console.WriteLine("创建日期:" + createTime);
}
}
class Vehicle
{
public string brand;
public double speed;
public double maxSpeed;
public double weight;
public void Run()
{
Console.WriteLine("车在跑");
}
public void Stop()
{
Console.WriteLine("刹车");
}
}
class Program
{
static void test02()
{
Vehicle car1 = new Vehicle();
car1.Run();
car1.Stop();
Vector3 v1 = new Vector3();
//v1.SetX(5.6);
v1.SetY(4.5);
v1.SetZ(8.45);
//Console.WriteLine(v1.GetX());
v1.SetX(-5);//默认是0,没有改变成负数
Console.WriteLine(v1.GetX());
Console.WriteLine(v1.Length());
}
static void test01()
{
Student stu1 = new Student();//声明对象+实例化对象
Student stu2;//声明对象
stu1.name = "李四";
stu1.address = "山西";
stu1.age = 18;
stu1.createTime = "11月23日";
stu1.Show();
stu2 = new Student();//实例化对象
}
static void Main(string[] args)
{
//test01();
test02();
}
}