using Syste
enum Color { Black, red, While, Yellow, Pink, Blue, Purple }
1、//class是关键字,用来定义一个类型
class Car {
//特征:颜色,价格,品牌
public Color color;
public double price;
public string brand;
//功能:刹车,行驶
//功能用方法来表示
}
class Tool
{
2、方法定义的语法格式;public返回值类型 方法名(形参列表){方法体}
3、方法是有特殊功能的代码块,方法的名字就是该代码块的名字,方法是一种代码重用机制
4、第一种方法类型:有参有返回值:
4.1如果有返回值,方法体里面一定要有return关键字,并且其后面只能跟一个值。
4.2返回值要和方法名前面的类型保持一致.
4.3当代码执行到return后,程序会跳出方法体,回到调用该方法的位置;
5练习
5.1第一题拼接两个字符串
public string Join_str(string a, string b) {
return a + b;
}
5.2第二题两个数比大小
public int Qiu_max(int a, int b) {
return a > b ? a : b;
}
5.4第三题计算累加和
public int Cumulative_sum(int n) {
int sum = 0;
for (int i = 0; i <= n; i++)
{
sum += i;
}
return sum;
}
5.5第四题计算某一天是年分中的第几天;
public bool is_leap_year(int year) {
return year % 400 == 0 || (year % 4 == 0 && year % 100 != 0) ? true : false;
}
public int How_Many_Day(int year, int mouth, int day) {
int[] mouth_day_list = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
mouth_day_list[1] = is_leap_year(year) ? 29 : 28;
int sum = 0;
for (int i = 0; i < mouth - 1; i++)
{
sum += mouth_day_list[i];
}
return sum + day;
}
6、第二种方法类型:有参无返回值;
6.1如果方法没有返回值,方法名前面的返回值使用void代替,方法体里面的return后面不加任何值;
6.2方法体里面的return如果在最后一行,当程序把方法里面的代码执行完以后,会自动跳到该方法的位置;
7、生活中的一些类
class pen
{
//特征;颜色,长短,大小
public Color color;
public int length;
public String tiji;
//功能:写字,画画
} class chair {
//特征:品牌,价格,高矮
public string pinpai;
public double price;
public string high;
//功能,休息,装饰
}
class JP {
//特征:价格,品牌,颜色
public double price;
public Color color;
public string pinpai;
//功能:打字
}
8、类和对象
8.1、如果是数值类型,默认值是0,如果是字符或者字符串,默认值为空
Car qiche = new Car();
qiche.brand = "五菱";
qiche.color = Color.While;
Console.WriteLine(qiche.brand);
8.2、方法是类里面的一个成员,故需要创建方法所在类的对象,通过对象使用点运算符调用
Tool tool=new Tool();
int a = 10, b = 20;
tool.Sumint(a, b);
int c = 30, d = 40;
tool.Sumint(c, d);
8.3调用方法要注意的事项,如果方法有返回值就定义一个和返回值类型一样的变量,接受返回值
8.4调用方法是传进来的数据都是有实际意义的,固调用时传进来的数据称为实参
8.5实参的类型以及个数要和形参一一对应。
int sum = tool.Qiu_max(2,3);
#endregion
int year=int.Parse (Console.ReadLine());
Console.WriteLine(tool. is_leap_year(year));
8.5调用方法时是先看方法名前面的返回值类型,如果是void,表示该方法没有返回值,就不用在定义变量接收返回值了,如果有返回值,就定一个和返回值类型一样的变量接收返回值
8.6再看方法名后边的参数,实参类型和个数要和形参一一对应。