主类的名字可以随便起,但是必须有主方法才能是主类
结构体中的方法:正常的方法的定义,但是要写在结构体中
运算符只要三个是从右向左结合的,分别是一元运算符,条件运算符,赋值运算符,其他都是从左向右
运算符的重载
1、 系统提供的运算符只能提供简单的数据类型的运算
2、 对自定义的类型不能操作
3、 如果想对自定义类型进行操作,需要对运算符进行重载(重新实现运算符的功能)
对运算符进行重载时
最重要的是牢记重载格式、明确你想要的返回值类型、参数列表不能一样,否则就成了同一个函数或方法(不要忘了写static)
pubic static 返回值类型operator 重载的运算符(类型1,类型2)所有的运算符的重载都为静态方法,需要使用public 关键字进行修饰。(一定不能忘了static)
public static Point operator+(Point p1,Point p2)//注意返回值类型和操作对象
{
int x = p1.x + p2.x;
int y = p1.y + p2.y;
Point temp = new Point(x, y);
return temp;
}
public static double operator-(Point p1,Point p2)
{
double x = (p1.x - p2.x) * (p1.x - p2.x);
double y = (p1.y - p2.y) * (p1.y - p2.y);
double dis =Math.Sqrt(x + y);//不要自己写函数,要利用系统的智能提示,这样不容易出现大小写错误;
return dis;
}
//函数名可以一样,但是参数列表不能一样
public static Point operator+(Point p1,int n)
{
// Point p2 = new Point(p1.x + n, p1.y+ n);
// return p2;
return new Point(p1.x + n, p1.y + n);
}
public static Point operator+(int n,Point p1)
{
return p1 + n;//可以直接调用之前的重载
}
class ClassMain
{
public static void Main()
{
Person p1 = newPerson("zhangsan", 20);
Person p2 = new Person("lisi", 25);
//返回真和假,c#真和假用bool类型表示。true真false假
if (p1 > p2)
{
Console.WriteLine("p1>p2");
}
else
{
Console.WriteLine("p1<p2");
}
}
}
struct Person
{
public string name;
public int age;
public Person (string _name ,int _age)
{
name = _name;
age = _age;
}
//关系运算符的重载,需要成对重载<, >要同时重载
public static bool operator>(Person p1,Person p2)
{
return p1.age > p2.age;
}
public static bool operator<(Person p1,Person p2)
{
return p1.age < p2.age;
}
}
//c#中switch与C语言相比可以使用字符串,整数值,可控类型
goto跳转到标记位置,不安全的跳转