Programme
/*
using System;
public class Test
{
static void Main()
{
float m = 0;
for (int i = 0; i < 20; i++)
{
float n = m + 0.25f * i;
Console.WriteLine("{0:N2} -> {1}", n, MathF.Round(n));//银行家舍入:四舍六入五取偶
}
}
}
*/
/*
using System;
public class Test
{
static void Main()
{
for (int i = 1; i <= 16; i++)
{
//ToString将数字转为16进制字符
Console.WriteLine("十进制: {0}\t十六进制: {1}\t十六进制占2位: {2}\t", i.ToString(), i.ToString("x"), i.ToString("x2"));
}
}
}
*/
/*
using System;
public class Test
{
static void Main()
{
//@可以保证后面的字符串取消转义
string str1 = @"E:\Visual Studio 2019\IDE\Common7\IDE";
//@可以保证后面的字符串是原内容输出
string str2 = @"春眠不觉晓,
处处闻啼鸟。";
//$使后面的字符串中可直接使用变量
int num = 520;
string str3 = $"Hello {num}";
Console.WriteLine(str1);
Console.WriteLine(str2);
Console.WriteLine(str3);
}
}
*/
/*
//计算语数英三科的平均成绩
using System;
public class Test
{
static void Main()
{
string name;
string math, chinese, english;
double mathScore = 0, chineseScore = 0, englishScore = 0;
bool correctEntered = true;
Console.WriteLine("What's ur name?");
name = Console.ReadLine();
Console.WriteLine("Enter ur math score:");
math = Console.ReadLine();
Console.WriteLine("Enter ur Chinese score:");
chinese = Console.ReadLine();
Console.WriteLine("Enter ur English score:");
english = Console.ReadLine();
//try-catch异常捕获:如果try中的代码出现异常(在这里是可能会接收到错误的成绩输入),将会立即跳转至catch中
try
{
mathScore = Convert.ToDouble(math);
chineseScore = Convert.ToDouble(chinese);
englishScore = Convert.ToDouble(english);
}
catch
{
correctEntered = false;
}
if (correctEntered)
{
double average = (mathScore + chineseScore + englishScore) / 3f;
Console.WriteLine($"So, {name}, your average score is {average}!");
}
else
{
Console.WriteLine("Please input correct grades!");
}
}
}
*/
/*
using System;
public class Test
{
static void Enter() => Console.WriteLine("Enter:");
static void Main()
{
int num1 = 520, num2 = 520, num3 = 520;
bool flag = true;
Enter();
num1 = Convert.ToInt32(Console.ReadLine());
Enter();
num2 = int.Parse(Console.ReadLine());
Enter();
flag = int.TryParse(Console.ReadLine(), out num3);//若转换成功,返回true并将num3设为转换成功的数字;若转换失败,返回false并将num3设为0
Console.WriteLine("num1 = " + num1);
Console.WriteLine("num2 = " + num2);
Console.WriteLine("num3 = " + num3);
Console.WriteLine("flag = " + flag);
}
}
*/
/*
//获取指定两个数字之间的任意一个随机数
using System;
public class Test
{
static void Main()
{
Random reandom = new Random();//创建Random类的实例
bool correctEntered = true;
int max = 0, min = 0;
try
{
Console.WriteLine("Enter the max:");
max = int.Parse(Console.ReadLine());
Console.WriteLine("Enter the min:");
min = int.Parse(Console.ReadLine());
}
catch
{
Console.WriteLine("Please enter 2 correct numbers!");
correctEntered = false;//数值输入错误
}
if (correctEntered)
{
if (min < max)
{
char ch = 'a';
while (ch != 'q')
{
int a = reandom.Next(min, max + 1);//获取一个随机数,左闭右开
Console.WriteLine("ENTER to get next number, Q to quit\n" + a);
ch = Console.ReadKey().KeyChar;
}
}
else
{
Console.Write("Please make sure max is bigger than min!");
}
}
Console.WriteLine("\nBye!");
}
}
*/
/*
using System;
public class Programme
{
enum Fruits { Apple, Banana }
//enum枚举类型,冒号后面是类型可选项,默认是int
enum ClothesSize : uint
{
Small = 1,
Regular = 2,
Large = 3
}
static void Main()
{
Console.WriteLine($"Apple is {Fruits.Apple}");
Console.WriteLine($"Banana is {Fruits.Banana}");
Console.WriteLine($"Apple is {(int)Fruits.Apple}");
Console.WriteLine($"Banana is {(int)Fruits.Banana}");
Console.WriteLine($"Small is {ClothesSize.Small}");
Console.WriteLine($"Regular is {ClothesSize.Regular}");
Console.WriteLine($"Large is {ClothesSize.Large}");
Console.WriteLine($"Small is {(uint)ClothesSize.Small}");
Console.WriteLine($"Regular is {(uint)ClothesSize.Regular}");
Console.WriteLine($"Large is {(uint)ClothesSize.Large}");
}
}
*/
/*
using System;
public class Test
{
enum QQState { Online, Offline }
static void Main()
{
//将数字强制转换为QQState类型
QQState state0 = (QQState)0;
QQState state1 = (QQState)1;
QQState state2 = (QQState)666;//如果无法转换,打印QQState实例时将会显示原数字
Console.WriteLine(state0);
Console.WriteLine(state1);
Console.WriteLine(state2);
//将string转换成QQState类型
QQState stateA = (QQState)Enum.Parse(typeof(QQState), "0");
QQState stateB = (QQState)Enum.Parse(typeof(QQState), "1");
QQState stateC = (QQState)Enum.Parse(typeof(QQState), "Online");
QQState stateD = (QQState)Enum.Parse(typeof(QQState), "Offline");
Console.WriteLine(stateA);
Console.WriteLine(stateB);
Console.WriteLine(stateC);
Console.WriteLine(stateD);
QQState stateE = (QQState)Enum.Parse(typeof(QQState), "233");//不合理的数字:不会产生异常,打印QQState实例时将会显示原数字
Console.WriteLine(stateE);
try
{
QQState stateF = (QQState)Enum.Parse(typeof(QQState), "HAHA");//不合理的文本:会产生异常
}
catch
{
Console.WriteLine("这儿有异常!");
}
}
}
*/
/*
using System;
public class Test
{
public enum Gender { male, female }
public struct Person
{
//结构体中字段要有访问修饰符
public string name;
public int age;
public Gender gender;
}
static void Main()
{
Person person1, person2;
person1.name = "Tom";
person1.age = 18;
person1.gender = Gender.male;
person2.name = "Lucy";
person2.age = 13;
person2.gender = Gender.female;
Console.WriteLine("{0} is {1}, {2} years old now.", person1.name, person1.gender, person1.age);
Console.WriteLine("{0} is {1}, {2} years old now.", person2.name, person2.gender, person2.age);
}
}
*/
/*
using System;
public class Test
{
static void Main()
{
//关于各类数组的初始化
int[] intArray = new int[5];
double[] doubleArray = new double[5];
bool[] boolArray = new bool[5];
string[] stringArray = new string[5];//会初始化所有的项为null(不分配内存空间)
Console.WriteLine("int类型数组:");
for (int i = 0; i < intArray.Length; i++)
{
Console.Write("{0} ", intArray[i]);
}
Console.Write("\n");
Console.WriteLine("double类型数组:");
for (int i = 0; i < doubleArray.Length; i++)
{
Console.Write("{0} ", doubleArray[i]);
}
Console.Write("\n");
Console.WriteLine("bool类型数组:");
for (int i = 0; i < boolArray.Length; i++)
{
Console.Write("{0} ", boolArray[i]);
}
Console.Write("\n");
Console.WriteLine("string类型数组:");
for (int i = 0; i < stringArray.Length; i++)
{
Console.Write("{0} ", stringArray[i]);
}
Console.Write("\n");
}
}
*/
/*
using System;
namespace Test
{
public class Programme
{
public struct Student
{
public string name;
public int age;
}
static void Main()
{
int a = 520;
Console.WriteLine(a.GetType().FullName);//默认返回命名空间.类名
Console.WriteLine(a.GetType().Name);//仅类名
Console.WriteLine(a.GetType().Namespace);//仅命名空间
Console.WriteLine(typeof(int).FullName);//默认返回命名空间.类名
Console.WriteLine(typeof(int).Name);//仅类名
Console.WriteLine(typeof(int).Namespace);//仅命名空间
bool b = true;
Console.WriteLine(b.GetType());
Console.WriteLine(typeof(bool));
char c = 'G';
Console.WriteLine(c.GetType());
Console.WriteLine(typeof(char));
string str = "Hello";
Console.WriteLine(str.GetType());
Console.WriteLine(typeof(string));
int[] arr = new int[2] { 0, 0 };
Console.WriteLine(arr.GetType());
Console.WriteLine(typeof(int[]));
Student stu = new Student();
stu.name = "小明";
stu.age = 18;
Console.WriteLine(stu.GetType().FullName);//默认返回命名空间.类名+结构名
Console.WriteLine(stu.GetType().Name);
Console.WriteLine(stu.GetType().Namespace);
Console.WriteLine(typeof(Student).FullName);//默认返回命名空间.类名+结构名
Console.WriteLine(typeof(Student).Name);
Console.WriteLine(typeof(Student).Namespace);
}
}
}
*/
/*
using System;
public class Test
{
static void Main()
{
//创建一个数组,然后为数组中每个元素赋值
int[] intArray1 = new int[10];
for(int i = 0; i < intArray1.Length; i++)
{
intArray1[i] = i + 1;
}
//初始化一个数组
int[] intArray2 = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
for (int i = 0; i < intArray1.Length; i++)
{
Console.Write("{0} ", intArray1[i]);
}
Console.Write("\n");
for (int i = 0; i < intArray2.Length; i++)
{
Console.Write("{0} ", intArray2[i]);
}
}
}
*/
/*
using System;
public class Test
{
static void Main()
{
int[] array = { 1, 5, 2, 5, 2, 1, 4, 2, 6, 2 };
Console.WriteLine("原始数组:");
for (int i = 0; i < array.Length; i++)
{
Console.Write("{0} ", array[i]);
}
Array.Sort(array);//数组排序
Console.WriteLine("\n排序后的数组:");
for (int i = 0; i < array.Length; i++)
{
Console.Write("{0} ", array[i]);
}
Array.Reverse(array);//数组倒置
Console.WriteLine("\n倒置后的数组:");
for (int i = 0; i < array.Length; i++)
{
Console.Write("{0} ", array[i]);
}
}
}
*/
/*
using System;
public class Test
{
public static int a = 666;
static void Main()
{
Console.WriteLine(a);
Func1();
Console.WriteLine(a);
Func2(a);//a作为参数传入Func2,被当做函数的局部变量,所以不改变静态字段a的值
Console.WriteLine(a);
}
static void Func1() => a++;
static void Func2(int num) => num++;
}
*/
/*
using System;
public class Test
{
//out参数类似C中的传址;必须在函数中对out参数赋值
public static void Func(out int a, out double b, out bool c, out string d)
{
a = 520;
b = 3.1415926;
c = true;
d = "Happy New Year!";
}
static void Main()
{
int a;
double b;
bool c;
string d;
Func(out a, out b, out c, out d);
Console.WriteLine(a);
Console.WriteLine(b);
Console.WriteLine(c);
Console.WriteLine(d);
}
}
*/
/*
using System;
public class Test
{
public static bool IsLogin(string account, string password, out string message)
{
if (account == "admin" && password == "12345")
{
message = "Login Successfully.";
return true;
}
else if (password == "12345")
{
message = "Wrong account.";
}
else if (account == "admin")
{
message = "Wrong password.";
}
else
{
message = "Wrong account and password.";
}
return false;
}
static void Main()
{
string account, password, message;
Console.WriteLine("Enter ur account:");
account = Console.ReadLine();
Console.WriteLine("Enter ur password:");
password = Console.ReadLine();
bool isLogin = IsLogin(account, password, out message);
if (isLogin)
{
Console.WriteLine("检测登录状态:成功!");
}
else
{
Console.WriteLine("检测登录状态:失败!");
}
Console.WriteLine(message);
}
}
*/
/*
using System;
public class Test
{
//ref参数要求进入函数前被赋值过
static void FunctionRef(ref int n)
{
//传入的参数必须保证已经赋值,ref可以保证参数是按引用传递进入函数的
n = 520;
n++;
}
//out参数要求在函数内部被赋值
static void FunctionOut(out int n)
{
n = 520;//无论传入的参数是否已经赋值,都会先被清空;所以必须在函数内部对out参数进行赋值
n++;
}
static void Main()
{
int a = 0;
FunctionRef(ref a);//ref是有进有出
Console.WriteLine(a);
int b;
FunctionOut(out b);//out是只出不进
Console.WriteLine(b);
}
}
*/
/*
using System;
public class Test
{
static void Main()
{
int a = 123, b = 456;
Console.WriteLine("a = {0}, b = {1}.", a, b);
Swap2(ref a, ref b);
Console.WriteLine("a = {0}, b = {1}.", a, b);
}
static void Swap2(ref int a, ref int b)
{
//交换两个数字的奇技淫巧
a -= b;
b += a;
a = b - a;
}
}
*/
/*
using System;
public class Time
{
int year, month, date, hour, minute, second;//默认的访问修饰符是private
public void DisplayCurrentTime()
{
Console.WriteLine("Stub code for DisplayCurrentTime.");//桩代码
}
}
public class Tester
{
static void Main()
{
Time t = new Time();
t.DisplayCurrentTime();
}
}
*/
/*
using System;
public class Time
{
//成员变量
private int year, month, date, hour, minute, second;
//方法
public void DisplayCurrentTime() => Console.WriteLine("{0}-{1}-{2} {3}:{4}:{5}", year, month, date, hour, minute, second);
public void GetTime(out int hour, out int minute, out int second)
{
hour = this.hour;
minute = this.minute;
second = this.second;
}
//构造函数:参数是一个DateTime结构体
public Time(DateTime dt)
{
year = dt.Year;
month = dt.Month;
date = dt.Day;
hour = dt.Hour;
minute = dt.Minute;
second = dt.Second;
}
}
public class Test
{
static void Main()
{
DateTime currentTime = DateTime.Now;//DateTime.Now是一个DateTime结构体
Time myTime = new Time(currentTime);
myTime.DisplayCurrentTime();
int theHour, theMinute, theSecond;
myTime.GetTime(out theHour, out theMinute, out theSecond);
Console.WriteLine("{0}:{1}:{2}", theHour, theMinute, theSecond);
}
}
*/
/*
using System;
public class Time
{
//私有成员变量
private int year, month, date, hour, minute, second;
//公共访问方法
public void DisplayCurrentTime() => Console.WriteLine("Current time is: {0}-{1}-{2} {3}:{4}:{5}", year, month, date, hour, minute, second);
//构造函数
public Time(DateTime dt)
{
//初始化成员变量
year = dt.Year;
month = dt.Month;
date = dt.Day;
hour = dt.Hour;
minute = dt.Minute;
second = dt.Second;
}
}
public class Test
{
static void Main()
{
while (true)
{
DateTime currentTime = DateTime.Now;//DateTime.Now是一个DateTime结构体
Time myTime = new Time(currentTime);
myTime.DisplayCurrentTime();
System.Threading.Thread.Sleep(1000);//namespace是System.Threading
}
}
}
*/
/*
using System;
public class Time
{
private int year, month, date, hour, minute, second;
public void DisplayCurrentTime()
{
DateTime now = DateTime.Now;
Console.WriteLine("Current time -> {0}-{1}-{2} {3}:{4}:{5}", now.Year, now.Month, now.Day, now.Hour, now.Minute, now.Second);
Console.WriteLine("Time received -> {0}-{1}-{2} {3}:{4}:{5}", year, month, date, hour, minute, second);
}
//通过传入DateTime结构来构造
public Time(DateTime dt)
{
year = dt.Year;
month = dt.Month;
date = dt.Day;
hour = dt.Hour;
minute = dt.Minute;
second = dt.Second;
}
//通过传入6个时间值来构造
public Time(int year, int month, int date, int hour, int minute, int second)
{
//this表示是Time这个类的成员
this.year = year;
this.month = month;
this.date = date;
this.hour = hour;
this.minute = minute;
this.second = second;
}
}
public class Test
{
static void Main()
{
DateTime currentTime = DateTime.Now;
Time time1 = new Time(currentTime);
Time time2 = new Time(1997, 12, 25, 23, 12, 0);
time1.DisplayCurrentTime();
time2.DisplayCurrentTime();
}
}
*/
/*
using System;
public class Test
{
public static int GetMax(int dumb, params int[] arr)//params可变参数:最后性,唯一性
{
int max = arr[0];
for(int i = 0; i < arr.Length; i++)
{
if (arr[i] > max)
{
max = arr[i];
}
}
return max;
}
static void Main()
{
int[] arr = { 1, 4, 2, 6, 4, 7, 8, 6 };
int max1= GetMax(666, arr);//实参可以是一个数组
int max2 = GetMax(666, 1, 4, 2, 6, 4, 7, 8, 6);//实参可以是若干数字
Console.WriteLine(max1);
Console.WriteLine(max2);
}
}
*/
/*
using System;
public class Test
{
//方法的重载
public static decimal Add(decimal a, decimal b)
{
return a + b;
}
public static decimal Add(decimal a, decimal b, decimal c)
{
return a + b + c;
}
public static float Add(float a, float b)
{
return a + b;
}
public static double Add(double a, double b)
{
return a + b;
}
static void Main()
{
decimal a = Add(1.0m, 2.0m);//小数加m后缀:表示decimal类型的数据
decimal b = Add(1.0m, 2.0m, 3.0m);
float c = Add(3.0f, 4.0f);
double d = Add(5.0, 6.0);
Console.WriteLine("{0}\n{1}\n{2}\n{3}", a, b, c, d);
}
}
*/
/*
using System;
public class Test
{
static void Main()
{
Print.PrintTitle();//如果使用所在类之外的静态方法,要用类名访问
for (int i = 0; i < 10; i++)
{
Console.WriteLine("The factorial of {0} is {1}.", i + 1, Factorial(i + 1));
}
}
public static int Factorial(int a) => (a == 0 || a == 1) ? 1 : a * Factorial(a - 1);
}
public class Print
{
public static void PrintTitle() => Console.WriteLine("Let's print the factorial of 1 - 10:");
}
*/
/*
using System;
class Programme
{
static void Main()
{
Console.WriteLine("Enter a number:");
int num = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Enter ur favourite fruit:");
string myFavouriteFruit = Console.ReadLine();
Console.WriteLine("");
switch (num)
{
case 1:
Console.WriteLine("1"); break;
case 2:
Console.WriteLine("2"); break;
default:
Console.WriteLine("Others"); break;//这里的break是必须要写的
}
Console.WriteLine("");
switch (num)
{
case 1:
case 2:
Console.WriteLine("1 or 2"); break;//这里和C语言一样,是或的关系
default:
Console.WriteLine("Others"); break;
}
Console.WriteLine("");
switch (num)
{
case 1:
Console.WriteLine("1");
goto case 2;//如果想从一个case跳到另一个case中,要使用goto显式跳转;goto代替了break
case 2:
Console.WriteLine("2");
goto default;//可以跳到任意一个位置的case中,或是default中
default:
Console.WriteLine("Others"); break;
}
Console.WriteLine("");
switch (myFavouriteFruit)//switch语句也支持判断string
{
case "Orange":
Console.WriteLine("U like orange!"); break;
case "Apple":
Console.WriteLine("U like apple!"); break;
default:
Console.WriteLine("U like other fruits!"); break;
}
}
}
*/
/*
using System;
class Programme
{
static void Main()
{
int i = 0;
repeat:
Console.WriteLine("i = {0}", i);
i++;
if (i <= 10)
{
goto repeat;//使用goto构成循环语句
}
}
}
*/
/*
using System;
class Programme
{
static void Main()
{
bool isPrime = true;
int ct = 0;//质数计数器
for (int i = 1; i <= 1000; i++)//输出1到1000的质数
{
for (int j = 2; j <= Math.Sqrt(i); j++)
{
if (i % j == 0)
{
isPrime = false;
break;
}
}
if (isPrime == true && i != 1)
{
Console.Write("{0}\t", i);
ct++;
if (ct % 10 == 0 && ct != 0)
{
Console.Write("\n");
}
}
isPrime = true;
}
}
}
*/
/*
using System;
class Programme
{
static void Main()
{
Console.WriteLine("B to break, others to continue");
Console.Write("Enter something here:");
string str = Console.ReadLine();
while (true)
{
if (str != "B")
{
Console.WriteLine("What U entered is {0}, now continue...", str);
Console.WriteLine("B to break, others to continue");
Console.Write("Enter something here:");
str = Console.ReadLine();
continue;//可以省略,此处是为了突出控制关系
}
else
{
Console.WriteLine("What U entered is {0}, now break!", str);
break;
}
}
}
}
*/
/*
using System;
class Programme
{
static void Main()
{
int i1 = 17, i2 = 4;
float f1 = 17.0f, f2 = 4.0f;
double d1 = 17.0, d2 = 4.0;
decimal dec1 = 17.0M, dec2 = 4.0M;//decimal要采用M作为后缀
Console.WriteLine("{0} {1} {2} {3}", i1 / i2, f1 / f2, d1 / d2, dec1 / dec2);//注意整数除法
}
}
*/
/*
using System;
class Programme
{
static void Main()
{
bool judge = true;
//短路原则
if ((2 > 1) || (judge = false))
{
;//Do nothing
}
Console.WriteLine(judge);
if ((2 < 1) && (judge = false))
{
;//Do nothing
}
Console.WriteLine(judge);
}
}
*/
/*
//预处理指令:#define #undef #if #elif #else #endif
//C#不支持宏定义;#define和#undef只能放在代码最开头
#define TEST
#undef TEST//定义完又取消了
#define TOM
#define TED
using System;
class Programme
{
static void Main()
{
int a;
#if TEST
a = 1;
#else
a = 2;
#endif
Console.WriteLine(a);
int b;
#if TOM
b = 1;//就近原则,只会选择一条路,然后到endif
#elif TED
b = 2;//没定义TOM,但定义了TED
#else
b = 3;//TOM和TED都没定义
#endif
Console.WriteLine(b);
}
}
*/
/*
using System;
public class Test
{
private int num;
public void Print() => Console.WriteLine("num = " + num);
//构造函数的重载
public Test(int a) => num = a;//构造函数1
public Test(int a, int b) => num = b;//构造函数2
}
public class Driver
{
static void Main()
{
//通过参数的数量来区分使用的构造函数
Test test1 = new Test(4);
Test test2 = new Test(1, 2);
test1.Print();
test2.Print();
}
}
*/
/*
using System;
public class Test
{
private int num;//默认初始化为0
private char ch = 'C';//手动初始化
public void Print() => Console.WriteLine("num = " + num + ", ch = " + ch);
//构造函数的重载
public Test(int input) => num = input;//构造函数1
public Test(char input) => ch = input;//构造函数2
}
public class Driver
{
static void Main()
{
//通过参数的类型来区分使用的构造函数
Test test1 = new Test(4);
Test test2 = new Test('G');
test1.Print();
test2.Print();
}
}
*/
/*
using System;
public class Test
{
private int num;
public void Print() => Console.WriteLine("num = " + num);
public Test(int input) => num = input;
//this引用的一个用途:从一个构造方法中调用另一个重载构造方法
public Test(int input1, int input2) : this(input2 - input1) {; }
}
public class Driver
{
static void Main()
{
Test test1 = new Test(4);
Test test2 = new Test(5, 6);
test1.Print();
test2.Print();
}
}
*/
/*
using System;
public class Class1
{
public void Func1(Class2 obj2) => obj2.Print();
}
public class Class2
{
private int a = 520;
public void Print() => Console.WriteLine(a);
//把当前对象(即调用Func2方法的对象)作为另一个方法(Func1)的参数
public void Func2(Class1 obj1) => obj1.Func1(this);
}
public class Test
{
static void Main()
{
Class1 myClass1 = new Class1();
Class2 myClass2 = new Class2();
myClass2.Func2(myClass1);
}
}
*/
/*
using System;
public class NotStatic
{
private int a = 233;
public void Func()
{
Console.WriteLine("Hello NotStatic!");
Console.WriteLine(a);
}
}
public static class Static
{
//静态类只能包含静态成员
private static int a = 520;
public static void Func()
{
Console.WriteLine("Hello Static!");
Console.WriteLine(a);
}
}
public class Test
{
static void Main()
{
//非静态类需要实例化
NotStatic myNotStatic = new NotStatic();
myNotStatic.Func();
//静态类无法实例化
Static.Func();
}
}
*/
/*
using System;
public class NotStatic
{
//实例数据
private int notStaticNum = 233;
//静态数据
private static int staticNum = 520;
//实例方法:可以直接访问实例数据或静态数据
public void Func1()
{
Console.WriteLine(notStaticNum);
Console.WriteLine(staticNum);
}
//静态方法:不能直接访问实例数据,只能直接访问静态数据
public static void Func2() => Console.WriteLine(staticNum);
}
public class Test
{
static void Main()
{
//在静态的Main方法中,不能直接访问Func1实例方法,所以必须要先将NotStatic类实例化
NotStatic myNotStatic = new NotStatic();
//通过实例访问实例成员
myNotStatic.Func1();
//通过类名访问静态成员
NotStatic.Func2();
}
}
*/
/*
using System;
public class MyClass
{
private static int staticNum = 0;
private int notStaticNum = 0;
public void Print() => Console.WriteLine("staticNum = {0}, notStaticNum = {1}", staticNum, notStaticNum);
public MyClass()
{
staticNum++;
notStaticNum++;
}
}
public class Test
{
static void Main()
{
//注意,这里自定义的构造函数代替了默认的构造函数
MyClass obj1 = new MyClass();
obj1.Print();
MyClass obj2 = new MyClass();
obj2.Print();
MyClass obj3 = new MyClass();
obj3.Print();
//结果分析:当类加载时,无论new出多少个实例,静态数据在内存中只会分配一个空间,故MyClass.a的值是会累加的
}
}
*/
/*
using System;
public class MyClass
{
private int a = 520;
private static int b;
public void Print() => Console.WriteLine("a = {0}, b = {1}", a, b);
//静态构造函数:不能含有访问修饰符、参数、重载;作用:初始化静态数据
static MyClass() => b = 233;
}
public class Test
{
static void Main()
{
MyClass obj = new MyClass();
obj.Print();
}
}
*/
/*
using System;
public class MyClass
{
private int a = 1;
public MyClass() => Console.WriteLine("我是实例构造方法!");
//当程序结束时,GC可能不会马上释放资源,此时可以使用析构函数去手动释放资源;析构函数很可能不会调用,它可以理解为最后一道保险丝
~MyClass() => Console.WriteLine("我是析构方法!");
}
public class Test
{
static void Main()
{
MyClass obj = new MyClass();
}
}
*/
/*
using System;
public class Time
{
//常量字段:声明字段的时候必须初始化;常量字段一定是静态的,不能用static修饰
public const int dumb = 233;
//只读字段:防止成员变量在外部被修改;只能在声明时或在构造函数中赋值
public static readonly int year;
public static readonly int month;
public static readonly int date;
public static readonly int hour;
public static readonly int minute;
public static readonly int second;
//静态构造函数
static Time()
{
DateTime dt = DateTime.Now;
year = dt.Year;
month = dt.Month;
date = dt.Day;
hour = dt.Hour;
minute = dt.Minute;
second = dt.Second;
}
}
public class Test
{
static void Main()
{
Console.WriteLine("现在是" + Time.year + "年");
}
}
*/
/*
using System;
public class GameValue
{
private int hp = 100;
public int HP//通过属性封装,保护字段,对字段的取值进行限制
{
get
{
return hp;
}
set
{
if (value < 0)
{
value = 0;
}
hp = value;
}
}
}
public class Test
{
static void Main()
{
GameValue myGameValue = new GameValue();
Console.WriteLine("Now HP = " + myGameValue.HP);
myGameValue.HP -= 40;
Console.WriteLine("Now HP = " + myGameValue.HP);
myGameValue.HP -= 70;
//myGameValue.HP变为-10 -> value=myGameValue.HP=-10 -> hp=value=0
Console.WriteLine("Now HP = " + myGameValue.HP);
}
}
*/
/*
using System;
public class Number
{
private int num = 520;
public int Num//属性本质上是方法
{
get//读取
{
if (num == 233)
{
return 666;
}
return num;
}
set//写入
{
if (value < 0)
{
value = 233;
}
num = value;
}
}
}
public class Test
{
static void Main()
{
Number myNumber = new Number();
Console.WriteLine(myNumber.Num);//读取
myNumber.Num = -100;//写入
Console.WriteLine(myNumber.Num);//读取
}
}
*/
/*
using System;
//子类继承父类的公有方法、属性和字段;子类不继承父类的构造函数,但会默认调用父类的无参数构造方法,创建父类对象,从而能访问父类中的成员
public class Person
{
//自动属性,作用等价于公共字段
public string Name { get; set; }
public char Gender { get; set; }
public int Age { get; set; }
public void Introduce() => Console.WriteLine("我是人类,我叫{0},我今年{1}岁,我是{2}性", Name, Age, Gender);
public Person(string name, int age, char gender) //父类构造函数
{
this.Name = name;
this.Age = age;
this.Gender = gender;
}
}
public class Student : Person
{
public int Score { get; set; }
public void StudentIntroduce() => Console.WriteLine("我叫{0},我今年{1}岁,我是{2}性,我成绩是{3}", Name, Age, Gender, Score);
public Student(string name, int age, char gender, int score) : base(name, age, gender)//在子类中显式调用父类的构造函数
{
this.Score = score;
}
}
public class Teacher : Person
{
public int Salary { get; set; }
public void TeacherIntroduce() => Console.WriteLine("我叫{0},我今年{1}岁,我是{2}性,我工资是{3}", Name, Age, Gender, Salary);
public Teacher(string name, int age, char gender, int salary) : base(name, age, gender)
{
this.Salary = salary;
}
}
public class Test
{
static void Main()
{
Student XiaoMing = new Student("小明", 18, '男', 98);
Teacher TeacherWang = new Teacher("王老师", 45, '女', 8000);
XiaoMing.Introduce();
TeacherWang.Introduce();
XiaoMing.StudentIntroduce();
TeacherWang.TeacherIntroduce();
}
}
*/
/*
using System;
public class Person
{
public int Age { get; set; }
public void Introduce() => Console.WriteLine("我是一名人类!");
}
public class Student : Person
{
//子类中的成员如果命名和父类中的某个成员相同(不一定要是同种成员),则会起到覆盖的效应
//规范做法:使用new关键字,显式隐藏父类中的同名成员
public new void Introduce() => Console.WriteLine("我是一名学生!");
//方法的重载
public void Introduce(int number) => Console.WriteLine("我喜欢数字" + number);
}
public class Test
{
static void Main()
{
Student stu = new Student();
stu.Introduce();
(stu as Person).Introduce();
stu.Introduce(520);
}
}
*/
/*
using System;
public class Fruit
{
public void FruitSayHello() => Console.WriteLine("Hi, I'm Fruit");
}
public class Pear : Fruit
{
public void PearSayHello() => Console.WriteLine("Hi, I'm Pear");
}
public class Peach : Fruit
{
public void PeachSayHello() => Console.WriteLine("Hi, I'm Peach");
}
public class Test
{
static void Main()
{
Fruit[] fruits = new Fruit[10];
Random rand = new Random();
for (int i = 0; i < 10; i++)
{
int seed = rand.Next(1, 4);//产生1到3
switch (seed)
{
case 1:
fruits[i] = new Pear();//子类可以用于为父类赋值(里氏转换)
break;
case 2:
fruits[i] = new Peach();//子类可以用于为父类赋值(里氏转换)
break;
default:
fruits[i] = new Fruit();
break;
}
}
for (int i = 0; i < 10; i++)
{
Pear tempPear;
Peach tempPeach;
if (fruits[i] is Pear)//is关键字用于检查父类能否被转换为子类
{
tempPear = (Pear)(fruits[i]);
tempPear.PearSayHello();//如果能转换,可将父类强转为子类(里氏转换)
}
else if (fruits[i] is Peach)
{
tempPeach = fruits[i] as Peach;//as可看做是is和强转的综合;如果无法转换,则返回null
tempPeach.PeachSayHello();
}
else//new Fruit()产生的Fruit类不能被转换为Pear类或Peach类
{
fruits[i].FruitSayHello();
}
}
}
}
*/
/*
using System;
public class Parent
{
public int hp;
}
public class Child : Parent
{
public int exp;
}
public class Test
{
static void Main()
{
Child child = new Child();
child.exp = 666;
child.hp = 100;
Console.WriteLine("Child: exp = {0}, hp = {1}", child.exp, child.hp);
Parent parent = child;
Console.WriteLine("Parent: hp = {0}", parent.hp);//父类无法逆向访问到子类的成员
child = parent as Child;
Console.WriteLine("Child: exp = {0}, hp = {1}", child.exp, child.hp);//子类转换为父类,并未丢失数据(exp的数据还在)
}
}
*/
/*
using System;
public class Test {
static void Main()
{
double n1 = 1.23;
decimal n2 = 3.12M;
char n3 = 'H';
string n4 = "Good";
bool n5 = false;
Console.WriteLine(n1.GetType());
Console.WriteLine(n2.GetType());
Console.WriteLine(n3.GetType());
Console.WriteLine(n4.GetType());
Console.WriteLine(n5.GetType());
//var代表推断类型,即通过值来确定类型;所以在声明推断类型时必须初始化
var m1 = 1.23;
var m2 = 3.12M;
var m3 = 'H';
var m4 = "Good";
var m5 = false;
Console.WriteLine(m1.GetType());
Console.WriteLine(m2.GetType());
Console.WriteLine(m3.GetType());
Console.WriteLine(m4.GetType());
Console.WriteLine(m5.GetType());
}
}
*/
/*
//多态:让一个对象表现出多种类型
using System;
public class Person
{
public string Name { get; set; }
public Person(string name) => this.Name = name;
//父类的虚方法,使用virtual关键字
public virtual void SayHello() => Console.WriteLine("我是人类,我叫" + this.Name);
}
public class Chinese : Person
{
public Chinese(string name) : base(name) {; }
//在子类中重写父类的方法,使用override关键字
public override void SayHello() => Console.WriteLine("我是中国人,我叫" + this.Name);
}
public class Test
{
static void Main()
{
Person per1 = new Person("李华");
Chinese ch1 = new Chinese("王梅");
Person per2 = new Chinese("张飞");//将子类赋值给父类
Chinese ch2 = (Chinese)per2;//将父类强转为子类
per1.SayHello();
ch1.SayHello();
per2.SayHello();//可以看出多态的效果
ch2.SayHello();
}
}
*/
/*
using System;
namespace iLoveCsharp
{
public class Class1//隐式继承于Object
{
//重写Object类的ToString虚方法
public override string ToString() { return "重写成功!"; }
}
public class Class2 { int dumb; }
public class Test
{
static void Main()
{
Class1 class1 = new Class1();
Class2 class2 = new Class2();
Console.WriteLine(class1.ToString());
Console.WriteLine(class2.ToString());
}
}
}
*/
/*
using System;
public class Test
{
//当父类中无需构写方法体时,可以使用抽象类实现多态
static void Main()
{
Animal[] animals = { new Cow(), new Dog(), new Cat() };
for (int i = 0; i < animals.Length; i++)
{
animals[i].Eat();
}
}
//abstract成员只能存在于abstract类中;修饰符abstract对于字段无效
public abstract class Animal//抽象类:无法实例化
{
public abstract void Eat();//抽象方法没有方法体
}
//在子类中重写父类方法时,要保证子类方法的签名与父类方法相同
public class Cow : Animal
{
public override void Eat() => Console.WriteLine("I eat grass");
}
public class Dog : Animal
{
public override void Eat() => Console.WriteLine("I eat meat");
}
public class Cat : Animal
{
public override void Eat() => Console.WriteLine("I eat fish");
}
}
*/
/*
using System;
public class Test
{
public abstract class Grandfather
{
//抽象类中可以包含实例成员,供继承的子类使用
public string Name { get; set; }
//抽象类不能被实例化,但可以有构造函数
public Grandfather(string name) => this.Name = name;
public abstract void SayHello();
}
//如果抽象父类的子类也是抽象类,不用重写抽象方法
public abstract class Father : Grandfather
{
public Father(string name) : base(name) {; }
public abstract void SayHi();
}
//如果子类不是抽象类,必须要重写父类的抽象方法
public class Son : Father
{
public Son(string name) : base(name) {; }
public override void SayHello() => Console.WriteLine("Hello");
public override void SayHi() => Console.WriteLine("Hi");
}
static void Main()
{
Son mySon = new Son("Mike");
Console.WriteLine(mySon.Name);
mySon.SayHello();
mySon.SayHi();
}
}
*/
/*
using System;
public class Test
{
//Test1:使用抽象类计算圆形和矩形的周长与面积
static void Main()
{
Shape[] shapes = { new Circle(1), new Rectangular(2, 3) };
Console.WriteLine("圆形的周长是{0:0.00},面积是{1:0.00}", shapes[0].GetPerimeter(), shapes[0].GetArea());
Console.WriteLine("矩形的周长是{0:0.00},面积是{1:0.00}", shapes[1].GetPerimeter(), shapes[1].GetArea());
}
//定义Shape抽象类
public abstract class Shape
{
public abstract double GetPerimeter();
public abstract double GetArea();
}
//定义Circle类
public class Circle : Shape
{
public double R;
public Circle(double r) => this.R = r;
public override double GetPerimeter()
{
return 2 * Math.PI * this.R;
}
public override double GetArea()
{
return Math.PI * this.R * this.R;
}
}
//定义Rectangular类
public class Rectangular : Shape
{
public double Length, Width;
public Rectangular(double length, double width)
{
this.Length = length;
this.Width = width;
}
public override double GetPerimeter()
{
return 2 * (this.Length + this.Width);
}
public override double GetArea()
{
return this.Length * this.Width;
}
}
}
*/
/*
using System;
public class Test
{
//Test2:使用抽象类,模拟各种RSD(U盘,移动硬盘,MP3)插入电脑读写的过程
static void Main()
{
Computer Lenovo = new Computer();
RSD[] rsds = { new Udisk(), new ProtableDisk(), new MP3() };
//模拟读写
for(int i = 0; i < rsds.Length; i++)
{
Lenovo.connectedRSD = rsds[i];
Lenovo.CpuRead();
Lenovo.CpuWrite();
}
((MP3)rsds[2]).PlayMusic();
}
}
//Removable Storage Device
public abstract class RSD
{
public abstract void Read();
public abstract void Write();
}
//U盘
public class Udisk : RSD
{
public override void Read() => Console.WriteLine("U盘正在读取数据...");
public override void Write() => Console.WriteLine("U盘正在写入数据...");
}
//移动硬盘
public class ProtableDisk : RSD
{
public override void Read() => Console.WriteLine("移动硬盘正在读取数据...");
public override void Write() => Console.WriteLine("移动硬盘正在写入数据...");
}
//MP3
public class MP3 : RSD
{
public override void Read() => Console.WriteLine("MP3正在读取数据...");
public override void Write() => Console.WriteLine("MP3正在写入数据...");
public void PlayMusic() => Console.WriteLine("MP3正在播放音乐...");
}
//电脑
public class Computer
{
public RSD connectedRSD { get; set; }
public void CpuRead() => connectedRSD.Read();
public void CpuWrite() => connectedRSD.Write();
}
*/
/*
public class Parent
{
public void MethodParent() => System.Console.WriteLine("I am parent");
}
internal class Son : Parent//子类的访问权限不能高于父类
{
public void MethodSon() => System.Console.WriteLine("I am son");
}
public class Test
{
static void Main()
{
Son mySon = new Son();
mySon.MethodSon();
mySon.MethodParent();
}
}
*/
/*
using System;
public class Test
{
static void Main()
{
Console.Write("Enter the fruit u want:");
string choice = Console.ReadLine();
Fruit fruitWanted = GetFruit(choice);
if (fruitWanted != null)
{
Console.Write("Hello! ");
fruitWanted.Introduce();
}
else
{
Console.Write("I dont know this fruit!");
}
}
//简单工厂设计模式:通过用户的输入来将不同的子类赋值给父类
public static Fruit GetFruit(string choice)//这里要写静态方法,不用实例化了
{
Fruit fruit = null;
switch (choice)
{
case "Orange":
fruit = new Orange(); break;
case "Apple":
fruit = new Apple(); break;
case "Banana":
fruit = new Banana(); break;
default:
break;//fruit=null
}
return fruit;
}
}
public abstract class Fruit
{
public abstract void Introduce();
}
public class Orange : Fruit
{
public override void Introduce() => Console.WriteLine("I'm Orange");
}
public class Apple : Fruit
{
public override void Introduce() => Console.WriteLine("I'm Apple");
}
public class Banana : Fruit
{
public override void Introduce() => Console.WriteLine("I'm Banana");
}
*/
/*
using System;
public class Test
{
static void Main()
{
Son son = new Son();
son.Func1();
son.Func2();
son.Func3();
son.SuperFunc();
//可以将继承于某个接口的子类实例化,赋给该接口对象
Interface1 interface1 = new Son();
Interface2 interface2 = new Son();
Interface3 interface3 = new Son();
SuperInterface superInterface = new Son();
//这样接口对象就可以调用自己的方法了
interface1.Func1();
interface2.Func2();
interface3.Func3();
superInterface.SuperFunc();
}
}
public class Parent
{
int dumbParent;
}
public class Son : Parent, SuperInterface//一个类只能继承一个父类,但能继承多个接口;当父类和接口同时存在时,要把继承的父类放在最前面
{
int dumbSon;
//在继承了某个接口的子类中,必须实现接口中所有的方法
public void Func1() => Console.WriteLine("Sup, I'm Func1");
public void Func2() => Console.WriteLine("Sup, I'm Func2");
public void Func3() => Console.WriteLine("Sup, I'm Func3");
public void SuperFunc() => Console.WriteLine("Sup, I'm SuperFunc");
}
public interface Interface1
{
void Func1();//接口相当于一种标准,其中的方法不能有方法体;接口不用于存储,其中不能包含字段;接口不能实例化,故无构造函数
}
public interface Interface2
{
void Func2();//接口中的成员不能设置访问修饰符,默认为public
}
public interface Interface3
{
void Func3();//接口中只能含有方法(无方法体),自动属性,索引器,事件
}
public interface SuperInterface : Interface1, Interface2, Interface3//一个接口可以继承多个其他的接口,但不能继承类
{
void SuperFunc();
}
*/
/*
using System;
public class Test
{
static void Main()
{
//调用类中的Eat方法
Person myClass = new Person();
myClass.Eat();
//调用接口中的Eat方法
IEatable myInterface = new Person();
myInterface.Eat();
}
}
public class Person : IEatable
{
public void Eat() => Console.WriteLine("我是Person类的方法!");
//显式实现接口:解决方法重名的问题
void IEatable.Eat() => Console.WriteLine("我是IEatable接口中方法的实现!");
}
public interface IEatable
{
void Eat();
}
*/
/*
using System;
public class Test
{
//可以用ref,out关键字实现:将按值传递改为按引用传递
static void Main()
{
int a = 123;
Console.WriteLine(a);
int b = a;//值传递,传递的只是值本身
b = 666;
Console.WriteLine(a);
Console.WriteLine(b);
Person person1 = new Person();
person1.Name = "张三";
Console.WriteLine(person1.Name);
Person person2 = person1;//引用传递,传递的是对于某个对象的引用
person2.Name = "李四";
Console.WriteLine(person1.Name);
Console.WriteLine(person2.Name);
string str1 = "Hello";
Console.WriteLine(str1);
string str2 = str1;//虽然string是引用类型,但是它比较特殊,当成值传递理解就好
str2 = "Good";//字符串具有不可变性:每次赋新的值,就会开辟新的空间
Console.WriteLine(str1);
Console.WriteLine(str2);
}
}
public class Person
{
public string Name { get; set; }
}
*/
/*
using System;
public class Test
{
static void Main()
{
Parent person = new Parent();
person.Name = "Tom";
person.Method();
Son son = new Son();
son.Name = "Jack";
son.Method();
}
}
//部分类,本质上是同一个类
public partial class Parent
{
public string Name { get; set; }
}
public partial class Parent
{
public void Method() => Console.WriteLine("Name is " + this.Name);
}
//密封类,不可被其他类继承,但可以继承别的类
public sealed class Son : Parent
{
int _dumb;
}
*/
/*
using System;
using System.Security.Cryptography;
using System.Text;
public class Test
{
static void Main()
{
Console.WriteLine("输入你要MD5加密的字符串:");
string str = Console.ReadLine();
string md5Str = GetMD5(str);
Console.WriteLine("加密为:" + md5Str);
}
//MD5加密:str -> 十六进制数字str
public static string GetMD5(string str)
{
MD5 md5 = MD5.Create();//MD5是一个抽象类,不能直接创建对象,要调用Create返回一个对象
//加密过程翻译的是字节数组
byte[] buffer = Encoding.Default.GetBytes(str);
byte[] md5Buffer = md5.ComputeHash(buffer);
//将结果转换为字符串
string md5Str = "";
for (int i = 0; i < md5Buffer.Length; i++)
{
md5Str += md5Buffer[i].ToString("x2");
}
return md5Str;
}
}
*/
/*
using System;
//可以设置C#允许不安全代码,然后定义一个unsafe类,便可使用指针
public unsafe class Test
{
static void Main()
{
int num = 520;
Console.WriteLine("Before, num is " + num);
Func(&num);
Console.WriteLine("Then, num is " + num);
}
public static void Func(int* p)
{
(*p)++;
}
}
*/
/*
using System;
public unsafe class Test
{
static void Main()
{
//定义一个二维数组
int[,] matrix =
{
{1, 2, 3, 4 },
{5, 6, 7, 8 },
{9, 10, 11, 12 },
{13, 14, 15, 16 }
};
//二维指针数组
int*[,] pMatrix = new int*[4,4];
//C#用fixed关键字标记一个指针的位置
fixed(int* ptr = &matrix[0, 0])
{
for(int i = 0; i < 4; i++)
{
for(int j = 0; j < 4; j++)
{
pMatrix[i, j] = ptr + (4 * i + j);
}
}
}
for (int i = 0; i < 4; i++)
{
for (int j = 0; j < 4; j++)
{
(*pMatrix[i, j])++;
}
}
for (int i = 0; i < 4; i++)
{
for (int j = 0; j < 4; j++)
{
Console.Write(matrix[i, j] + " ");
}
Console.WriteLine("");
}
}
}
*/
/*
using System;
public class Test
{
static int? num = 233;//可空值类型
static void Main()
{
Console.WriteLine("A: " + num);
Console.WriteLine("B: " + num.Value);//访问值时要用Value
Console.WriteLine("C: " + num.HasValue);
Console.WriteLine("D: " + num.GetValueOrDefault(666));
num = null;
Console.WriteLine("E: " + num);
Console.WriteLine("F: " + num.HasValue);
Console.WriteLine("G: " + num.GetValueOrDefault(666));
}
}
*/
/*
using System;
public class Driver
{
static void Main()
{
int length = 5;
Test test = new Test(length);
test[0] = "Tom";
test[1] = "Jack";
for (int i = 0; i < length; i++)
{
Console.WriteLine(test[i]);
}
Console.WriteLine(test["Tom"]);
Console.WriteLine(test["Jack"]);
Console.WriteLine(test["Catty"]);
}
}
public class Test
{
private string[] nameList;//访问nameList时,类似通过属性访问私有字段
public Test(int length)
{
nameList = new string[length];
for (int i = 0; i < length; i++)
{
nameList[i] = "N/A";
}
}
//索引器Indexer:通过下标获得元素
public string this[int index]
{
get { return (index >= 0 && index <= nameList.Length - 1) ? nameList[index] : ""; }//读取
set//写入
{
if (index >= 0 && index <= nameList.Length - 1)
nameList[index] = value;
}
}
//重载索引器:通过搜索元素匹配下标
public int this[string str]
{
get
{
for (int i = 0; i < nameList.Length; i++)
{
if (str == nameList[i])
{
return i;
}
}
return -1;//如果搜索不到
}
}
}
*/
/*
using System;
public class Test
{
static void Main()
{
Box box1 = new Box(1, 2, 3);
Box box2 = new Box(4, 5, 6);
Box box3 = box1 + box2;
Console.WriteLine($"length: {box3.length}\nwidth: {box3.width}\nheight: {box3.height}");
}
}
public class Box
{
public float length;
public float width;
public float height;
public float GetVolume() => length * width * height;
//运算符重载
public static Box operator +(Box box1, Box box2)
=> new Box(box1.length + box2.length, box1.width + box2.width, box1.height + box2.height);
public Box(float length, float width, float height)
{
this.length = length;
this.width = width;
this.height = height;
}
}
*/
/*
using System;
public class MyList<T>//对类使用泛型
{
public T[] list;
public MyList(int n) => list = new T[n];
public T GetItem(int n) => list[n];
public void SetItem(int n, T value) => list[n] = value;
}
public class Test
{
delegate T MyDelegate<T>(T t);//对委托使用泛型
static void Main()
{
MyList<char> myList = new MyList<char>(5);
for (int i = 0; i < 5; i++)
{
myList.SetItem(i, (char)('a' + i));//char可以和int直接相加减
}
for (int i = 0; i < 5; i++)
{
Console.Write($"{myList.GetItem(i)} ");
}
int a = 233;
int b = 520;
Swap<int>(ref a, ref b);
Console.Write($"{a} {b} ");
MyDelegate<int> myDelegate;//定义委托变量
myDelegate = (n) => { return n * 100; }; //myDelegate = delegate (int n) { return n * 100; };
Console.Write(myDelegate(1));
}
static void Swap<T>(ref T a, ref T b)//对方法使用泛型
{
T temp = a;
a = b;
b = temp;
}
}
*/
/*
using System;
using System.Diagnostics;
public class Test
{
[Conditional("DEBUG")]//特性:仅在Debug模式下才可以调用
public static void Function1(string str) => Console.WriteLine(str);
[Conditional("RELEASE")]//特性:仅在Release模式下才可以调用
public static void Function2(string str) => Console.WriteLine(str);
[Obsolete("Please use Function4 instead.", false)]//特性:弃用某个方法
public static void Function3(string str) => Console.WriteLine(str);
public static void Function4(string str) => Console.WriteLine(str);
static void Main()
{
Function1("I am in debug mode!");
Function2("I am in release mode!");
Function3("Haha");
}
}
*/
/*
using System;
//类名必须是以Attribute结尾
[AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = false)]
public class HelpAttribute : Attribute
{
string description;
public string Description => description;//位置参数:positional parameter;是必须的
public HelpAttribute(string str) => description = str;
public string Name { get; set; }//命名参数:named parameter;非必须的
}
[Help("Hello", Name = "ysysr2002")]
public class Test { }
public class Driver
{
static void Main()
{
//反射
HelpAttribute helpAttribute;
foreach(var i in typeof(Test).GetCustomAttributes(true))
{
helpAttribute = i as HelpAttribute;
if (helpAttribute != null)
{
Console.WriteLine($"Description: {helpAttribute.Description}\nName: {helpAttribute.Name}");
}
}
}
}
*/
String
/*
using System;
public class Test
{
//修改一个字符串中的若干个字符:str.ToCharArray(),new string(charArray)
static void Main()
{
string str = "abcdefg";//字符串是只读的,不能直接修改字符
PrintStr(str);
char[] charArray = str.ToCharArray();//将string转换为char数组
charArray[0] = 'h';
str = new string(charArray);//利用构造函数,将char数组转换为string
PrintStr(str);
}
static void PrintStr(string str)
{
for (int i = 0; i < str.Length; i++)
{
Console.Write(str[i]);
}
Console.Write('\n');
}
}
*/
/*
using System;
public class Test
{
static void Main()
{
Console.WriteLine("输入一段英文:");
string str = Console.ReadLine();
Console.WriteLine("转换为大写是:" + str.ToUpper());
Console.WriteLine("转换为小写是:" + str.ToLower());
}
}
*/
/*
using System;
using System.Text;
using System.Diagnostics;
public class Test
{
static void Main()
{
const int cycleTimes = 50000;//循环次数
string str = null;
Stopwatch sw = new Stopwatch();//创建一个计时器
TimeSpan ts1, ts2;//用于分别记录两种操作经历的时间
sw.Start();
for (int i = 1; i <= cycleTimes; i++)//采用传统方法进行字符串的拼接任务,会很耗时间,因为会不断开辟新的内存
{
str += (i + " ");
if (i % 20 == 0)
{
str += '\n';
}
}
sw.Stop();
ts1 = sw.Elapsed;
Console.WriteLine(str);
sw.Reset();//注意要使用Reset重置;使用Restart可以重新开始
str = null;
StringBuilder sb = new StringBuilder();
sw.Start();
for (int i = 1; i <= cycleTimes; i++)
{
sb.Append(i + " ");
if (i % 20 == 0)
{
sb.Append('\n');
}
}
sw.Stop();
ts2 = sw.Elapsed;
Console.WriteLine(sb.ToString());//最终还是要将StringBuilder转换为string
Console.WriteLine("string花费时间:" + ts1);
Console.WriteLine("StringBuilder花费时间:" + ts2);
}
}
*/
/*
using System;
public class Test
{
static void Main()
{
Console.WriteLine("输入第一句话:");
string str1 = Console.ReadLine();
Console.WriteLine("输入第二句话:");
string str2 = Console.ReadLine();
//比较字符串
if (str1.Equals(str2, StringComparison.OrdinalIgnoreCase))//忽略大小写比较两个字符串
{
Console.WriteLine("{0} and {1} is same!", str1, str2);
}
else
{
Console.WriteLine("{0} and {1} is not same!", str1, str2);
}
}
}
*/
/*
using System;
public class Test
{
static void Main()
{
string str = "1 2 3 +4 5 %6 7= _8, 9";
string[] forSplit = { " ", "+", "=", "_", "%", "," };//也可以用char数组
//去除字符串中的指定元素
string[] strArray = str.Split(forSplit, StringSplitOptions.RemoveEmptyEntries);//不将空串作为一个元素添加到string数组中
str = null;
for (int i = 0; i < strArray.Length; i++)
{
str += strArray[i];
}
Console.WriteLine(str);
}
}
*/
/*
using System;
public class Test
{
static void Main()
{
Console.WriteLine("输入一段话:");
string str = Console.ReadLine();
if (str.Contains("tmd"))//判断字符串是否包含指定子字符串
{
str = str.Replace("tmd", "***");//替换子字符串
}
if (str.Contains("sb"))
{
str = str.Replace("sb", "**");
}
Console.WriteLine(str);
}
}
*/
/*
using System;
public class Test
{
static void Main()
{
Console.WriteLine("输入一段话,可以以xxx为开头或结尾:");
string str = Console.ReadLine();
if (str.StartsWith("xxx"))
{
Console.WriteLine("是以xxx为开头的!");
}
if (str.EndsWith("xxx"))
{
Console.WriteLine("是以xxx为结尾的!");
}
if (str.StartsWith("xxx") && str.EndsWith("xxx") && str.Length > 6)
{
string strInput = str.Substring(3, str.Length - 6);//起始索引,数量
Console.WriteLine("你发现了彩蛋!你输入的是" + strInput);
}
}
}
*/
/*
using System;
public class Test
{
static void Main()
{
string str = "天天都要像今天这样天真无邪哦!你要天天开心!";
int index_天 = str.IndexOf("天");//返回第一个"天"的索引位置
Console.WriteLine("天的索引如下所示:");
while (true)
{
Console.Write(index_天 + " ");
index_天++;
index_天 = str.IndexOf("天", index_天);//第二个参数用来表示起始搜索的位置,这样利用循环就可以搜索全部的索引了
if (index_天 == -1)//如果找不到则返回-1
{
Console.Write("\n");
break;
}
}
str = @"C:\asdf\asfdsafd\afsad\fdg\sfad\asdf\akk.avi";
int index = str.LastIndexOf("\\");
str = str.Substring(index + 1);
Console.WriteLine(str);
}
}
*/
/*
using System;
public class Test
{
static void Main()
{
string str = null;
if (string.IsNullOrEmpty(str))
{
Console.WriteLine("Bingo!");
}
str = "";
if (string.IsNullOrEmpty(str))
{
Console.WriteLine("Bingo!");
}
str = " hhh hhh ";
Console.WriteLine("---" + str.Trim() + "---");//去除字符串前后所有空格
Console.WriteLine("---" + str.TrimStart() + "---");//去除字符串前面所有空格
Console.WriteLine("---" + str.TrimEnd() + "---");//去除字符串后面所有空格
string[] strArr = { "Apple", "Pear", "Melon", "Orange" };
str = String.Join(",", strArr);
Console.WriteLine(str);
str = String.Join("->", "Apple", "Pear", "Melon", "Orange");//参数二由paramas修饰
Console.WriteLine(str);
}
}
*/
/*
using System;
public class Test
{
static void Main()
{
Console.WriteLine("输入一段英文,以空格分开单词:");
string str = Console.ReadLine();
string[] strs = str.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
Array.Reverse(strs);//数组倒置
str = String.Join(" ", strs);
Console.WriteLine(str);
}
}
*/
IO
/*
using System;
using System.IO;
public class Test {
static void Main()
{
//Path类是静态类,可以用其中的一些方法对路径string进行快速的操作
string path = @"E:\Visual Studio 2019\IDE\Common7\IDE\devenv.exe";
string temp;
temp = Path.GetFileName(path);//获取文件名,包含扩展名
Console.WriteLine(temp);
temp = Path.GetFileNameWithoutExtension(path);//获取文件名,不包含扩展名
Console.WriteLine(temp);
temp = Path.GetExtension(path);//获取文件扩展名
Console.WriteLine(temp);
temp = Path.GetDirectoryName(path);//获取文件所在目录
Console.WriteLine(temp);
temp = Path.GetFullPath(path);//获取文件完整路径
Console.WriteLine(temp);
temp = Path.Combine(@"E:\Visual Studio 2019\", @"IDE\Common7\IDE\devenv.exe");//拼凑路径
Console.WriteLine(temp);
}
}
*/
/*
using System;
using System.IO;
using System.Text;
public class Test
{
static void Main()
{
//新建文件 File.Create
//删除文件 File.Delete
//移动文件 File.Move
//复制文件 File.Copy
string path1 = @"C:\Users\岳双阳\Desktop\File1.txt";
string path2 = @"C:\Users\岳双阳\Desktop\File2.txt";
string path3 = @"C:\Users\岳双阳\Desktop\File3.txt";
string path4 = @"C:\Users\岳双阳\Desktop\File4.txt";
Console.WriteLine("采用ReadAllLines的方法读取:");
string[] strs = File.ReadAllLines(path1, Encoding.Default);//将内容存为string数组
foreach(string item in strs)
{
Console.WriteLine(item);
}
Console.WriteLine("采用ReadAllText的方法读取:");
string str = File.ReadAllText(path1, Encoding.Default);//将内容存为string
Console.WriteLine(str);
Console.WriteLine("采用ReadAllBytes的方法读取:");
byte[] buffer = File.ReadAllBytes(path1);//将内容存为byte数组 -> 其中换行(\r\n)被存为两个字节
str = Encoding.Default.GetString(buffer);//将byte数组的内容转成string
Console.WriteLine(str);
Console.WriteLine("采用WriteAllBytes的方法写入!");
buffer = Encoding.Default.GetBytes(str);//将string内容转成byte数组
File.WriteAllBytes(path2, buffer);//把byte数组写入到文件中
Console.WriteLine("采用WriteAllLines的方法写入!");
File.WriteAllLines(path3, new string[] { "Hello", "Good", "Morning" });
Console.WriteLine("采用WriteAllText的方法写入!");
File.WriteAllText(path4, "I love you Baby!");
Console.WriteLine("采用AppendAllText的方法追加!");
File.AppendAllText(path4, "I'm the guy appended!");
}
}
*/
/*
using System;
using System.IO;
using System.Text;
public class Test
{
static void Main()
{
string path1 = @"C:\Users\岳双阳\Desktop\File1.txt";
FileStream fsRead = new FileStream(path1, FileMode.OpenOrCreate, FileAccess.Read);//创建一个文件流对象
byte[] buffer = new byte[1024 * 1024 * 2];//创建一个2MB大小的缓冲区
int read = fsRead.Read(buffer, 0, buffer.Length);//返回的read是实际读取到的数据的字节数
string str = Encoding.Default.GetString(buffer, 0, read);
Console.WriteLine("str: {0}", str);
fsRead.Close();//关闭文件流
fsRead.Dispose();//GC不会自动释放文件流产生的资源
//将创建FileStream对象的过程写在using框架中,会自动关闭和释放资源
using (FileStream fsWrite = new FileStream(path1, FileMode.OpenOrCreate, FileAccess.Write))
{
str = "jj";
buffer = Encoding.Default.GetBytes(str);
fsWrite.Write(buffer, 0, buffer.Length);//会从前往后覆盖
}
}
}
*/
/*
using System;
using System.IO;
using System.Text;
public class Test
{
static void Main()
{
string path1 = @"C:\Users\岳双阳\Desktop\File1.txt";
using (FileStream fs = new FileStream(path1, FileMode.OpenOrCreate, FileAccess.Read))
{
byte[] buffer = new byte[12];//UTF8存储字符是1-4个字节,所以缓冲区可以设置成12字节
while (true)
{
Console.WriteLine("当前光标位置:" + fs.Position);//Positon属性可以记录光标的实时位置
int read = fs.Read(buffer, 0, buffer.Length);//offset始终为0就可以了
if (read == 0)
{
break;
}
string str = Encoding.Default.GetString(buffer, 0, read);
Console.WriteLine(str);
}
}
}
}
*/
/*
using System;
using System.IO;
public class Test
{
//Test1:文件复制器
static void Main()
{
string src = @"C:\Users\岳双阳\Desktop\数据结构和算法.url";
string dest = @"C:\Users\岳双阳\Desktop\副本.url";
using (FileStream fsRead = new FileStream(src, FileMode.Open, FileAccess.Read))//创建读取流
{
using (FileStream fsWrite = new FileStream(dest, FileMode.OpenOrCreate, FileAccess.Write))//创建写入流
{
byte[] buffer = new byte[1024 * 1024 * 3];//一次读取3MB
while (true)
{
int read = fsRead.Read(buffer, 0, buffer.Length);
if (read == 0)
{
Console.WriteLine(Path.GetFileName(src) + "已复制成功!");
break;
}
fsWrite.Write(buffer, 0, read);
}
}
}
}
}
*/
/*
using System;
using System.IO;
using System.Text;
public class Test
{
static void Main()
{
string path1 = @"C:\Users\岳双阳\Desktop\File1.txt";
using (StreamReader sr = new StreamReader(path1, Encoding.Default))//创建一个读取流
{
while (!sr.EndOfStream)//如果没到文件末尾
{
Console.WriteLine(sr.ReadLine());
}
}
using (StreamWriter sw = new StreamWriter(path1, true))//创建一个写入流,参数true表示追加模式
{
sw.WriteLine("Look at me");
}
}
}
*/
/*
using System;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
public class Test
{
static void Main()
{
string path1 = @"C:\Users\岳双阳\Desktop\File1.txt";
Person personSet = new Person();
personSet.Age = 19;
personSet.Name = "张三";
using (FileStream fsWrite = new FileStream(path1, FileMode.OpenOrCreate, FileAccess.Write))
{
//序列化(Serialize):将对象转为二进制数据
BinaryFormatter bf = new BinaryFormatter();
bf.Serialize(fsWrite, personSet);
}
using (FileStream fsRead = new FileStream(path1, FileMode.OpenOrCreate, FileAccess.Read))
{
//反序列化(Deserialize):将二进制数据转为对象
BinaryFormatter bf = new BinaryFormatter();
object obj = bf.Deserialize(fsRead);//返回一个object类型的值
Person personGet = (Person)obj;
Console.WriteLine("Name:" + personGet.Name + " Age:" + personGet.Age);
}
}
}
[Serializable]//将一个类标记为可序列化
public class Person
{
public int Age { get; set; }
public string Name { get; set; }
}
*/
Collection
/*
using System;
using System.Collections;
namespace Hello
{
public class Test { private int num = 520; }
public class Driver
{
static void Main()
{
//单个元素:默认打印的是元素的值
int intNum = 233;
double doubleNum = 3.14;
bool isUsed = true;
string str = "Hello";
//集合元素:默认打印的是命名空间+类名
int[] intArray = { 1, 2, 3, 4, 5 };
ArrayList list = new ArrayList();
Test myTest = new Test();
list.Add(intNum);
list.Add(doubleNum);
list.Add(isUsed);
list.Add(str);
list.Add(intArray);
list.Add(list);//ArrayList也可以存放集合自身
list.Add(myTest);
for (int i = 0; i < list.Count; i++)//集合里的Count相当于数组里的Length
{
Console.WriteLine(list[i]);
}
}
}
}
*/
/*
using System;
using System.Collections;
public class Test
{
static void Main()
{
ArrayList list = new ArrayList();
list.Add("Hello!");//添加单个元素
list.AddRange(new int[] { 1, 2, 3, 4, 5 });//添加集合元素:数组、ArrayList;会将集合中的元素逐个添加
list.AddRange(list);//先将list拆分,再将拆分出的元素逐个存入list
for (int i = 0; i < list.Count; i++)
{
Console.WriteLine(list[i]);
}
Console.WriteLine("");
list.Clear();//清空集合中的所有元素
list.Add("HaHa!!!");
list.Insert(0, "Smith");//将单个元素插入至指定索引处
list.InsertRange(0, new string[] { "Good", "Morning", "Miss" });//将集合元素插入至指定索引处
for (int i = 0; i < list.Count; i++)
{
Console.WriteLine(list[i]);
}
Console.WriteLine("");
list.Remove("Good");//根据内容删除单个元素,注意如果有重复元素只能删除其中的一个
list.RemoveAt(0);//根据索引删除单个元素
list.RemoveRange(0, 2);//根据索引和数量删除多个元素
for (int i = 0; i < list.Count; i++)
{
Console.WriteLine(list[i]);
}
Console.WriteLine("");
list.Clear();
list.AddRange(new int[] { 5, 2, 3, 4, 3, 1 });
list.Sort();//升序排列元素(如果无法排序会报错)
list.Reverse();//将元素倒置
if (list.Contains(1))//检查集合中是否含有某元素
{
Console.WriteLine("list中含有1");
}
for (int i = 0; i < list.Count; i++)
{
Console.Write(list[i] + " ");
}
}
}
*/
/*
using System;
using System.Collections;
public class Test
{
static void Main()
{
//Count是集合实时的元素数量,Capacity是容量;当集合容量不够时,会从4开始,成倍地扩容
ArrayList list = new ArrayList();
Console.WriteLine("Count = {0}, Capacity = {1}", list.Count, list.Capacity);
list.AddRange(new int[] { 1 });
Console.WriteLine("Count = {0}, Capacity = {1}", list.Count, list.Capacity);
list.AddRange(new int[] { 1, 1, 1, 1 });
Console.WriteLine("Count = {0}, Capacity = {1}", list.Count, list.Capacity);
list.AddRange(new int[] { 1, 1, 1, 1 });
Console.WriteLine("Count = {0}, Capacity = {1}", list.Count, list.Capacity);
list.AddRange(new int[] { 1, 1, 1, 1, 1, 1, 1, 1 });
Console.WriteLine("Count = {0}, Capacity = {1}", list.Count, list.Capacity);
list.Clear();//清空之后Capacity不变
Console.WriteLine("Count = {0}, Capacity = {1}", list.Count, list.Capacity);
}
}
*/
/*
using System;
using System.Collections;
public class Test
{
static void Main()
{
ArrayList list = new ArrayList();
Random rand = new Random();
//该方法很低效
for (int i = 0; i < 1000;)
{
int seed = rand.Next(1, 1001);//1到1000
if (!list.Contains(seed))
{
list.Add(seed);
i++;
}
}
for (int i = 0; i < list.Count; i++)
{
Console.Write("{0} ", list[i]);
if (i % 20 == 0 && i != 0)
{
Console.Write("\n");
}
}
}
}
*/
/*
using System;
using System.Collections;
public class Test
{
static void Main()
{
int[] arr = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
foreach(var i in arr)//foreach用于遍历集合对象中的元素
{
Console.WriteLine(i);
}
Console.WriteLine("");
ArrayList arrList = new ArrayList();//ArrayList:集合
arrList.Add(520);
arrList.AddRange(new string[] { "Happy", "Good" });
foreach (var i in arrList)
{
Console.WriteLine(i);
}
Console.WriteLine("");
Hashtable hTable = new Hashtable();//Hashtable:键值对集合
hTable.Add("Hello", 123);
hTable.Add(true, 'c');
hTable.Add(1.23M, 1.23);
hTable.Add("haha", "coco");
hTable.Remove("haha");//根据键删除某个键值对
hTable["Hello"] = 666;//此法可为某键重新赋值;如果使用Add试图添加一个键已存在的键值对,则会报错;如果没有"Hello"的键,那此法就等效于Add
foreach (var i in hTable.Keys)//遍历键值对集合中的所有键
{
Console.WriteLine("键是{0},值是{1}", i, hTable[i]);
}
foreach (var i in hTable.Values)//遍历键值对集合中的所有值
{
Console.WriteLine("值是{0}", i);
}
if (hTable.ContainsKey(true))
{
Console.WriteLine("包含true这个键");
}
if (hTable.ContainsValue(1.23))
{
Console.WriteLine("包含1.23这个值");
}
hTable.Clear();//清空键值对集合
}
}
*/
/*
using System;
using System.Collections;
public class Test
{
//通过Hashtable将输入的小写字母转为大写字母
static void Main()
{
string lower = "abcdefghijklmnopqrstuvwxyz";
string upper = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
Console.WriteLine("输入:");
string input = Console.ReadLine();
Hashtable hTable = new Hashtable();
//将每个小写字母和大写字母绑定成为一个键值对
for (int i = 0; i < lower.Length; i++)
{
hTable[lower[i]] = upper[i];
}
Console.WriteLine("转换之后为:");
for (int i = 0; i < input.Length; i++)
{
if (hTable.ContainsKey(input[i]))
{
Console.Write(hTable[input[i]]);
}
else
{
Console.Write(input[i]);
}
}
}
}
*/
/*
using System;
using System.Collections.Generic;
using System.Linq;
public class Test
{
static void Main()
{
//和ArrayList十分类似,List也有以下方法可以使用:
//Remove RemoveAt RemoveRange
//Insert InsertRange
//Reverse Sort
List<int> list = new List<int>();//泛型集合(变长数组)
list.Add(1);
list.AddRange(new int[] { 2, 3 });
list.AddRange(list);
foreach(var item in list)
{
Console.WriteLine(item);
}
Console.WriteLine("");
int[] arr = list.ToArray();//可以将泛型集合转为数组
for(int i = 0; i < arr.Length; i++)
{
Console.WriteLine(arr[i]);
}
Console.WriteLine("");
list = arr.ToList();//也可以将数组转为泛型集合
for(int i = 0; i < list.Count; i++)
{
Console.WriteLine(list[i]);
}
Console.WriteLine("");
List<string> listString = new List<string>();
listString.Add("Hello");
listString.Add("Hi");
listString.Add("Holiday");
for (int i = 0; i < listString.Count; i++)
{
Console.WriteLine(listString[i]);
}
}
}
*/
/*
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
public class Test
{
static void Main()
{
//如果两个对象存在继承关系,可能会发生装箱拆箱的操作
object obj;
int m = 520;
obj = m;//将值类型赋给引用类型(装箱)
m = (int)obj;//将引用类型赋给值类型(拆箱)
Console.WriteLine(m);
Stopwatch sw = new Stopwatch();
ArrayList arrList = new ArrayList();
List<int> list = new List<int>();
sw.Start();
for(int i = 0; i < 100000000; i++)
{
arrList.Add(i);//装箱
}
sw.Stop();
Console.WriteLine("ArrayList的时间:" + sw.Elapsed);
sw.Restart();
for (int i = 0; i < 100000000; i++)
{
list.Add(i);//没装箱
}
sw.Stop();
Console.WriteLine("List的时间:" + sw.Elapsed);
}
}
*/
/*
using System;
using System.Collections.Generic;
public class Test
{
static void Main()
{
//数组
//集合
//键值对集合 哈希表
//泛型集合 变长数组
//泛型键值对集合 字典集合
Dictionary<int, string> dic = new Dictionary<int, string>();//字典集合
dic.Add(1, "Good");
dic.Add(2, "Bad");
dic.Add(3, "Excellent");//其他方法参考哈希表
foreach (KeyValuePair<int,string> kvp in dic)//新的键值对遍历方式
{
Console.WriteLine("key is {0}, value is {1}.", kvp.Key, kvp.Value);
}
}
}
*/
/*
using System;
using System.Collections.Generic;//泛型集合
public class Test
{
//嵌套字典
static void Main()
{
Dictionary<string, Dictionary<string, string>> info = new Dictionary<string, Dictionary<string, string>>();
info.Add("Geralt", new Dictionary<string, string>());
info["Geralt"].Add("Weapon", "Sword");
info["Geralt"].Add("Money", "10000");
info["Geralt"].Add("Level", "50");
Console.WriteLine(info["Geralt"]["Weapon"]);
Console.WriteLine(info["Geralt"]["Money"]);
Console.WriteLine(info["Geralt"]["Level"]);
}
}
*/
/*
using System;
using System.Collections;
public class Test
{
//Test1:将一个数组中的奇数放到一个集合中,偶数放到另一个集合中;再将两个集合合并(奇数在前边)
static void Main()
{
int[] arr = { 32, 1, 312, 42, 31, 45, 2, 623, 1, 432, 1 };
ArrayList odd = new ArrayList();
ArrayList even = new ArrayList();
ArrayList all = new ArrayList();
foreach (var i in arr)
{
if (i % 2 == 0)
even.Add(i);
else
odd.Add(i);
}
foreach (var i in odd)
all.Add(i);
foreach (var i in even)
all.Add(i);
Console.WriteLine("odd ArrayList:");
for (int i = 0; i < odd.Count; i++)
Console.Write("{0} ", odd[i]);
Console.WriteLine("\neven ArrayList:");
for (int i = 0; i < even.Count; i++)
Console.Write("{0} ", even[i]);
Console.WriteLine("\nall ArrayList:");
for (int i = 0; i < all.Count; i++)
Console.Write("{0} ", all[i]);
}
}
*/
/*
using System;
using System.Collections.Generic;
public class Test
{
//Test2:用户输入一个句子,判断每个字符出现的次数
static void Main()
{
Console.WriteLine("输入一句话:");
string input = Console.ReadLine();
Dictionary<char, int> htCharAmount = new Dictionary<char, int>();//创建<字符,出现次数>键值对集合
for(int i = 0; i < input.Length; i++)
{
if (!htCharAmount.ContainsKey(input[i]))
{
htCharAmount.Add(input[i], 1);
}
else
{
htCharAmount[input[i]]++;
}
}
foreach (KeyValuePair<char, int> kvp in htCharAmount)
{
Console.WriteLine("{0}出现了{1}次", kvp.Key, kvp.Value);
}
}
}
*/
/*
using System;
using System.Collections.Generic;
public class Test
{
//Test3:获取指定范围[start,end]内的若干个不重复随机数
static void Main()
{
List<int> randNums = GetRandomNums(1, 10, 10);
for(int i = 0; i < randNums.Count; i++)
{
Console.WriteLine(randNums[i]);
}
}
public static List<int> GetRandomNums(int start, int end, int nums)
{
if ((start > end) || (nums > end - start + 1))
{
return null;
}
List<int> whole = new List<int>();
for (int i = start; i <= end; i++)
{
whole.Add(i);
}
List<int> result = new List<int>();
int randIndex, temp;
Random rand = new Random();
int ct = whole.Count;
for (int i = 0; i < nums; i++)
{
randIndex = rand.Next(0, ct);
result.Add(whole[randIndex]);
if (randIndex != ct - 1)
{
temp = whole[randIndex];
whole[randIndex] = whole[ct - 1];
whole[ct - 1] = temp;
}
ct--;
}
return result;
}
}
*/
/*
using System;
using System.Collections.Generic;
public class Test
{
static void Main()
{
Stack<int> nums = new Stack<int>();
for(int i = 0; i < 10; i++)
{
nums.Push(i + 1);//压栈
}
Console.WriteLine("读取不删除:");
for (int i = 0; i < 10; i++)
{
Console.WriteLine(nums.Peek());//读顶栈
Console.WriteLine("当前长度:" + nums.Count);
}
Console.WriteLine("读取并删除:");
for (int i = 0; i < 10; i++)
{
Console.WriteLine(nums.Pop());//弹栈
Console.WriteLine("当前长度:" + nums.Count);
}
}
}
*/
/*
using System;
using System.Collections.Generic;
public class Test
{
static void Main()
{
Queue<int> nums = new Queue<int>();
for (int i = 0; i < 10; i++)
{
nums.Enqueue(i + 1);//加入队列
}
Console.WriteLine("读取不删除:");
for (int i = 0; i < 10; i++)
{
Console.WriteLine(nums.Peek());//读取顶部数据
Console.WriteLine("当前长度:" + nums.Count);
}
Console.WriteLine("读取并删除:");
for (int i = 0; i < 10; i++)
{
Console.WriteLine(nums.Dequeue());//读取并删除顶部数据
Console.WriteLine("当前长度:" + nums.Count);
}
}
}
*/
SupermarketFramework
/*
using System;
using System.Collections.Generic;
//超市项目框架
public class Test
{
static void Main()
{
Console.WriteLine("欢迎光临");
Supermarket sm = new Supermarket();
sm.ShowProdus();
sm.ShoppingGuide();
}
}
//商品类
public class Product
{
public string ID { get; set; }//商品唯一编号
public string Name { get; set; }//商品名称
public double Price { get; set; }//商品单价
public Product(string id, string name, double price)
{
this.ID = id;
this.Name = name;
this.Price = price;
}
}
public class BookBag : Product
{
public BookBag(string id, string name, double price) : base(id, name, price) { }
}
public class Clothes : Product
{
public Clothes(string id, string name, double price) : base(id, name, price) { }
}
public class Milk : Product
{
public Milk(string id, string name, double price) : base(id, name, price) { }
}
public class Laptop : Product
{
public Laptop(string id, string name, double price) : base(id, name, price) { }
}
//仓库类
public class Storehouse
{
List<List<Product>> list = new List<List<Product>>();//List<Product>是一个货架,List<List<Product>>是总仓库
//构造函数:创建仓库时有4个货架,分别摆放4种商品
public Storehouse()
{
for(int i = 0; i < 4; i++)
{
list.Add(new List<Product>());
}
}
//进货:向某个货架上放置货物
public void PurchaseProducts(string strType, int count)
{
for(int i = 0; i < count; i++)
{
switch (strType)
{
//可以使用Guid生成一个唯一的编码
case "BookBag":
list[0].Add(new Product(Guid.NewGuid().ToString(), "书包", 110)); break;
case "Clothes":
list[1].Add(new Product(Guid.NewGuid().ToString(), "衣服", 230)); break;
case "Milk":
list[2].Add(new Product(Guid.NewGuid().ToString(), "牛奶", 10)); break;
case "Laptop":
list[3].Add(new Product(Guid.NewGuid().ToString(), "笔记本电脑", 7000)); break;
}
}
}
//拿货:从仓库中取出特定数量的某货物
public Product[] GetProducts(string strType, int count)
{
Product[] products = new Product[count];
int choice = 0;//根据strType来决定choice
for (int i = 0; i < count; i++)
{
switch (strType)
{
case "BookBag":
choice = 0; break;
case "Clothes":
choice = 1; break;
case "Milk":
choice = 2; break;
case "Laptop":
choice = 3; break;
default:
choice = 0; break;
}
//每次都会拿第一个
products[i] = list[choice][0];
list[choice].RemoveAt(0);
}
return products;
}
//查看货物
public void ShowProducts()
{
foreach(var item in list)
{
Console.WriteLine("目前仓库中有{0}件{1},单价是{2}", item.Count, item[0].Name, item[0].Price);
}
}
}
//超市类
public class Supermarket
{
//创建一个超市时,需要先进货到仓库里面
Storehouse sh = new Storehouse();
public Supermarket()
{
sh.PurchaseProducts("BookBag", 1000);
sh.PurchaseProducts("Clothes", 900);
sh.PurchaseProducts("Milk", 5000);
sh.PurchaseProducts("Laptop", 100);
}
//导购
public void ShoppingGuide()
{
Console.WriteLine("您需要什么货物?");
Console.WriteLine("我们有:BookBag,Clothes,Milk,Laptop");
string strType = Console.ReadLine();
Console.WriteLine("您需要几件呢?");
int count = Convert.ToInt32(Console.ReadLine());
Product[] products = sh.GetProducts(strType, count);//从仓库中调货
double sum = CulculateMoney(products);
Console.WriteLine("输入您的折扣方式:1.不使用优惠 2.打85折 3.打9折 4.满100元减10元 5.满300元减50元");
string discountChoice = Console.ReadLine();
Discount dis = null;//创建打折父类(抽象类)
switch (discountChoice)
{
case "1":
dis = new ByRate(1); break;
case "2":
dis = new ByRate(0.85); break;
case "3":
dis = new ByRate(0.9); break;
case "4":
dis = new ByMinus(100, 10); break;
case "5":
dis = new ByMinus(300, 50); break;
default:
dis = new ByRate(1); break;
}
double after = dis.GetDiscount(sum);
Console.WriteLine("您总共需要支付{0}元,折扣后需支付{1}元", sum, after);
Console.WriteLine("以下是您本次的购物信息:");
foreach(var i in products)
{
Console.WriteLine("商品名称:{0} 单价:{1} 商品编码:{2}", i.Name, i.Price, i.ID);
}
Console.WriteLine("欢迎下次光临");
}
//计算价格
public double CulculateMoney(Product[] products)
{
double sum = 0;
for(int i = 0; i < products.Length; i++)
{
sum += products[i].Price;
}
return sum;
}
//在超市中调用仓库的打印方法
public void ShowProdus()
{
sh.ShowProducts();
}
}
//折扣类
public abstract class Discount
{
public abstract double GetDiscount(double before);
}
public class ByRate : Discount//根据折扣率
{
public double Rate { get; set; }
public ByRate(double rate)
{
this.Rate = rate;
}
public override double GetDiscount(double before)
{
return before * Rate;
}
}
public class ByMinus : Discount//满减:满M元减N元
{
public double M { get; set; }
public double N { get; set; }
public ByMinus(double M, double N)
{
this.M = M;
this.N = N;
}
public override double GetDiscount(double before)
{
return before - (int)(before / M) * N;
}
}
*/