本文已参与「新人创作礼」活动,一起开启掘金创作之路。
C#面向对象
类的用法
类的申明
class 类名
{
}
例如:我们创建一个汽车的类
class Car
{
}
类的命名一般使用首字母大写其余字母小写的方式,而且类的修饰符为 class
类的成员
字段
字段是可以作为全局变量的一种变量;再C#中,经常使用字段来进行全局变量的申明;
static double r;
const double PI = 3.1415;
static void Main(string[] args)
{
Console.Write("请输入");
Program.r = Convert.ToDouble(Console.ReadLine());
Console.WriteLine("圆的面积为" + PI * Math.Pow(r, 2));
Console.ReadLine();
}
***
在变量的申明中添加 static 的关键字,说明我们定义的变量是一个静态变量;
属性
属性提供对类的访问。类的属性一般描写的是状态信息, 属性的语法
【权限修饰符】【类名】 【属性名】
{
get{get访问器}
set{set访问器}
}
get 访问器相当于一个没有参数的方法; set 访问器相当于一个有参数或者参数为VOID的方法;
里氏变换
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace 里氏转换
{
class Program
{
static void Main(string[] args)
{
Person[] pers = new Person[10];
Random r = new Random();
for (int i = 0; i < pers.Length; i++)
{
int rNumber = r.Next(1, 7);
switch (rNumber)
{
case 1: pers[i] = new Student();
break;
case 2: pers[i] = new Teacher();
break;
case 3: pers[i] = new MeiNv();
break;
case 4: pers[i] = new ShuaiGuo();
break;
case 5: pers[i] = new YeShou();
break;
case 6: pers[i] = new Person();
break;
}
}
for (int i = 0; i < pers.Length; i++)
{
if (pers[i] is Student)
{
((Student)pers[i]).StudentSayHello();
}
else if (pers[i] is Teacher)
{
((Teacher)pers[i]).TeacherSayHello();
}
else if(pers[i] is MeiNv)
{
((MeiNv)pers[i]).MeiNvSayHello();
}
else if (pers[i] is ShuaiGuo)
{
((ShuaiGuo)pers[i]).ShuaiGuoSayHello();
}
else if (pers[i] is YeShou)
{
((YeShou)pers[i]).YeShouSayHello();
}
else
{
pers[i].PersonSayHello();
}
// pers[i].PersonSayHello();
}
// string.Join()
Console.ReadKey();
}
}
public class Person
{
public void PersonSayHello()
{
Console.WriteLine("1");
}
}
public class Student : Person
{
public void StudentSayHello()
{
Console.WriteLine("11");
}
}
public class Teacher:Person
{
public void TeacherSayHello()
{
Console.WriteLine("111");
}
}
public class MeiNv : Person
{
public void MeiNvSayHello()
{
Console.WriteLine("1111");
}
}
public class ShuaiGuo : Person
{
public void ShuaiGuoSayHello()
{
Console.WriteLine("11111");
}
}
public class YeShou : Person
{
public void YeShouSayHello()
{
Console.WriteLine("111111");
}
}
}