C sharp(二)
一.class和struct
Class
using System;
class Dog //定义一个狗类
{
int age;
public string name;
public const int maxage=100; //公共常量
public static bool swim=true; //静态变量
public static void Write()
{
Console.WriteLine("嘉然小姐的狗捏");
}
}
Dog dog=new dog();
dog.name="嘉心糖";
partical修饰符
第一个cs文件
public partial class A
{
int a1;
}
第二个cs文件
public partial class A
{
int a2;
}
等于
public class A
{
int a1;
int a2;
}
partical class Dog
{
public void SetAge(int value)
{
this.age=value;
}
public static SetAge(Dog _this,int value)
{
_this.age=value;
} //静态方法属于类,非静态方法属于变量
public Dog()
{
this.age=21;
this.name="";
}
public Dog(string name)
{
this.age=21;
this.name=name;
} //构造函数可以理解为初始化,无返回值。
}
Dog dog0=new Dog();
Dog dog1=new Dog("嘉心糖");
Dog dog2=new Dog("顶碗人");
Dog.SetAge(dog0,20);//静态函数
dog0.SetAge(20);//调用函数
Struct
struct Dog2
{
//格式同class
}
Struct是值类型,class是引用类型
struct 在栈中进行内存分配,函数调用完后回收,class是在堆中分配,在C#运行中回收。
函数调用过程中,class复制地址,即复制后的变量数值变了,复制前的也要变。struct是复制数据,不影响复制前的。
如果想要struct也可以被修改,则加个ref。
二.继承
class B:A{
}
类型B继承自类型A,A叫做父类,B叫做子类
B从A中继承属性和方法。
using system;
partical class Hero{
int health;
int power;
public Hero{
this.health=100;
}
public void heal{
health +=10;
}
public void Attack
{
Console.WriteLine($"{name}使用水溅跃,无事发生");
}
}
class JiaXintang : Hero{
public override heal{
health +=100; //嘉心糖恢复的更快捏
}
public void skill1{
this.power=100;
this.Attack;
}
}
父类引用可以存储子类对象:
Hero peopele1=new JiaXintang();//嘉心糖是英雄,但英雄不一定是嘉心糖
所有类型的基类System.Object
public class object{
}