类和对象
1.创建类(一个文件里可以包含多个类)
在文件里点添加类即可
class Customer{
//定义一个类
public string name;
public string address;
public int age;
//定义方法
public void Show(){
Console.WriteLine("名字:name);
Console.WriteLine("地址:address);
Console.WriteLine("年龄:”+age);
Console.WriteLine("创建时间:+ createTime);
}
}
2.创建对象(在main方法里)
//利用类创建对象, c1就是对象名 Customer c1 = new Customer(); //Customer c2;//声明对象 //c2 = new Customer();//实例化一个对象 //对象的使用 c1.name ="siki"; c1.address ="北京"; c1.age = 20; c1.createTime="2021年"; c1.Show(); //调用
Math.Sqrt(x * x + y * y + z * z);//可以求长度
get和set
private:私有的,只能在这个类的内部访问
private float x;
private float y;
private float z;
//设置set来从外界取得它的值
public void SetX(float temp){
//如果想要x的值大于0,可以在方法里设置
if(temp<0){
return;
}
x = temp;
}
public void SetY(float temp){
y = temp;
}
public void SetZ(float temp){
z = temp;
}
//通过get方法输出值
public float getX(){
return x;
}
//在外界通过set方法设置值
v1.SetX(2.3f);
v1.SetY(4.5f);
v1.Setz(6.7f);
//访问值
Console.WriteLine(v1.getX());
Console.WriteLine(v1.Length());
构造函数(每个类必须要有)
系统会帮忙构造一个无参的构造函数(当我们创建一个对象的时候就会调用)
//无参
public Customer(){
Console,WriteLine("我是无参构造函数");
}
//有参
public Customer(string argl,string arg2, int arg3, string arg4){
name = arg1;
address = arg2;
age = arg3;
createTime = arg4;
}
//在main里传入对象
Customer zhangsan = new Customer("张三","三里屯",20,"2021年");
zhangsan.Show();
注意:它会自己调用相匹配的构造函数
this关键字
public string name;
public string address;
private int age;
public string createTime;
//如果参数名与成员名重名怎么办。
//this代表当前对象
public Customer(string name,string address, int age, string createTime){
this.name = name;//this.name代表成员名,name代表参数
}
属性
private string name;
private string address;
private int age;
private string createTime;
//属性
public void SetAge(int age){
this.age = age;
}
public int GetAge(){
return age;
}
//以上换个属性方法(get,set的简写)
public int Age{
//也可以单独设置get,set的访问权限
(private) get{
return age;
}
set{//value参数
//要设置年龄大于0的话
if(value<0)return;
age = value;
}
}
//main方法里
Customer lisi = new Customer();
//原本的调用和访问
//lisi.SetAge(23);
//Console.WriteLine(lisi.GetAge());
//新属性的调用和访问
lisi.Age = 34;
Console.WriteLine(lisi.Age);
//如果只提供一个set或者get,它就是只写或只读

被折叠的 条评论
为什么被折叠?



