C#语言基础
lesson#6 类和面向对象编程
内容:
1. 类;
2. 对象;
3. 类成员:字段,方法;
1,类
{
enum Color
{
Black,
Red,
White,
Yellow,
Pink,
Blue,
Purple
}
//class是关键字,用来定义一个类型
class Car
{
//特征:颜色,价格,品牌,
//功能:刹车,行驶,开门,加油
//功能用方法来表示
public Color color;
public double price;
public string brand;
}
class Tool
{
//方法定义的语法格式:
//public返回值类型 方法名(形参列表){方法体}
//方法体是有特殊功能的代码块,方法的名字就是该代码块的名字,方法是一种代码重用机制
//第一种方法类型:有参有返回值
//如果有返回值,方法体里面一定要有return关键字,并且其后面只能跟一个值
//返回值的类型要和方法名前面的类型保持一致
//当代码执行到return后,程序会跳出方法体,回到调用该方法的位置
public int SumInt(int a, int b)
{
int sum = a + b;
return sum;
}
//第二种方法类型:有参无返回值
//如果方法没有返回值,方法名前面的返回值类型用void代替,方法体里面的return后面不加任何值;
//方法体里面的return如果在最后一行,则可以省略不写,当程序把方法体里面的代码执行完以后,会自动跳到调用该方法的位置
public void PrinyIntArray(int[] x)
{
foreach (var item in x)
{
Console.WriteLine(item);
}
return;
}
}
class Homework
{
//编程定义一个方法,功能是把两个字符串进行拼接,得到一个新的字符串;
public string SumString(string x, string y)
{
string sum2 = x + y;
return sum2;
}
//定义一个方法,比较两个int类型的数据,得到其最大值;
public int Max(int q,int w)
{
int max = 0;
if (q>w)
{
max = q;
}
else
{
max = w;
}
//int max=a>b?a:b;
return max;
}
//编写方法int SumValue(int n);计算1+...+n的和;
public int SumValue(int n)
{
int sum = 0;
for (int i = 1; i <= n; i++)
{
sum = sum+i;
}
return sum;
}
//编写方法DayOfYear(year,month,day),得到参数day是year里面的第几天;
public int DayOfYear(int year, int month, int day)
{
int sum = 0;
int[] months = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
if (month==1)
{
sum = day;
}
else if (month == 2)
{
sum = 31 + day;
}
else
{
for (int i = 0; i < month-1; i++)
{
sum += months[i];
}
sum = sum + day;
if (year % 4 == 0 && year % 100 != 0 || year % 400 == 0)
{
sum++;
}
}
return sum;
}
}
class Students
{
//特征:身高,性别,年龄
//功能:唱歌,爱好,目标
public string tall;
public string gender;
public string age;
}
class Book
{
//特征:科目,大小,厚度
//功能:有声朗诵,看,翻页
public string subject;
public string size;
public string thick;
}
2,对象
class Program
{
static void Main(string[] args)
{
#region 类和对象
////如果是数值类型,默认值是0,如果是字符或者字符串,默认值为空
//Car qiche = new Car();