C#代码集

C#代码集C#入门代码示例记录一、示例静态计算工具类1publicstaticclassCalculator2{3publicstaticdoubleAdd(doublea,doub

大家好,又见面了,我是你们的朋友全栈君。

C#入门代码示例记录

一、示例静态计算工具类

 1 public static class Calculator
 2     {
 3         public static double Add(double a,double b)
 4         {
 5             return a + b;
 6         }
 7 
 8         public static double Sub(double a,double b)
 9         {
10             return a - b;
11         }
12 
13         public static double Mull(double a,double b)
14         {
15             return a * b;
16         }
17 
18         public static double Div(double a,double b)
19         {
20             if(b==0)
21             {
22                 return double.PositiveInfinity;
23             }
24             else
25             {
26                 return a / b;
27             }
28         }
29 }

调用类中的方法,由于是静态类,类在被加载的时候就完成了初始化,在静态储存区域中开辟了独立的空间进行存储。

 class Program
    {
        static void Main(string[] args)
        {
            double result = Calculator.Div(2, 0);
            Console.WriteLine(result);
        }
    }

二、窗体显示

       Form Myform1;
            Form Myform2;
            Myform1 = new Form();
            Myform2 = Myform1;
            Myform1.Text = "My Form!";
            Myform2.Text = "Happy Birthday!";
            Myform1.ShowDialog();

三、简单方法,简单递归,简单循环(累加)

    class Program
    {
        static void Main(string[] args)
        {
            calculator cal = new calculator();
            int sum01 = cal.GetSumByFor(100);
            Console.WriteLine("sum = " + sum01);
            int sum02 = cal.GetSumByMath(100);
            Console.WriteLine($"sum = {sum02}");
            int sum03 = cal.GetSumByRecursion(100);
            Console.WriteLine($"sum = {sum03}");
            // Console.ReadLine();
        }
    }
    class calculator
    {
    
public int GetSumByFor(int num) { int sum = 0; for (int i = 0; i < num + 1; i++) { sum += i; } return sum; } public int GetSumByRecursion(int num) { if (num == 1) return num; else { return num + GetSumByRecursion(num - 1); } } public int GetSumByMath(int num) { int result = (1 + num) * num / 2; return result; } }

简单递归应用(汉诺塔)

 class Program
    {
        static void Main(string[] args)
        {
            HanoiTowerPro A = new HanoiTowerPro();
            ulong result = A.Han(64);
            Console.WriteLine("An=" + result);
        }
    }
    class HanoiTowerPro
    {
        public ulong Han(ulong x)
        {
            if(x==1)
            {
                return 1;

            }
            else
            {
                ulong result = 2 * Han(x - 1) + 1;
                return result;
            }
        }
    }

四、示例构造器(构造器的定义)

class Student
{
    public Student()
    {
        this.Stu_ID = "001";
        this.Stu_Name = "No NAME!";
    }

    public Student(string ID, string Name)
    {
        this.Stu_ID = ID;
        this.Stu_Name = Name;
    }

    public string Stu_ID;
    public string Stu_Name;
}

构造器的调用

class Program
    {
        static void Main(string[] args)
        {
            Student Stu1 = new Student();
            Console.WriteLine(Stu1.Stu_ID);
            Console.WriteLine(Stu1.Stu_Name);
            Console.WriteLine("======================");
            Student Stu2 = new Student("002", "Shixuan Liu");
            Console.WriteLine(Stu2.Stu_ID);
            Console.WriteLine(Stu2.Stu_Name);

        }
    }

五、方法的简单应用,以及方法嵌套(计算圆面积,圆柱体积,圆锥体积)

class Program
    {
        static void Main(string[] args)
        {
            Calculator Result = new Calculator();
            double FinalResult = Result.GetConeVolume(100, 10);
            Console.WriteLine(FinalResult);
        }
    }
    class Calculator
    {
        public double GetcircleArea(double r)
        {
            return Math.PI * r * r;
        }

        public double GetCylinderVolume(double r,double h)
        {
            return GetcircleArea(r) * h;
        }

        public double GetConeVolume(double r,double h)
        {
            return GetCylinderVolume(r, h) / 3;
        }
    }

 

————恢复内容开始————

C#入门代码示例记录

一、示例静态计算工具类

 1 public static class Calculator
 2     {
 3         public static double Add(double a,double b)
 4         {
 5             return a + b;
 6         }
 7 
 8         public static double Sub(double a,double b)
 9         {
10             return a - b;
11         }
12 
13         public static double Mull(double a,double b)
14         {
15             return a * b;
16         }
17 
18         public static double Div(double a,double b)
19         {
20             if(b==0)
21             {
22                 return double.PositiveInfinity;
23             }
24             else
25             {
26                 return a / b;
27             }
28         }
29 }

调用类中的方法,由于是静态类,类在被加载的时候就完成了初始化,在静态储存区域中开辟了独立的空间进行存储。

 class Program
    {
        static void Main(string[] args)
        {
            double result = Calculator.Div(2, 0);
            Console.WriteLine(result);
        }
    }

二、窗体显示

       Form Myform1;
            Form Myform2;
            Myform1 = new Form();
            Myform2 = Myform1;
            Myform1.Text = "My Form!";
            Myform2.Text = "Happy Birthday!";
            Myform1.ShowDialog();

三、简单方法,简单递归,简单循环(累加)

    class Program
    {
        static void Main(string[] args)
        {
            calculator cal = new calculator();
            int sum01 = cal.GetSumByFor(100);
            Console.WriteLine("sum = " + sum01);
            int sum02 = cal.GetSumByMath(100);
            Console.WriteLine($"sum = {sum02}");
            int sum03 = cal.GetSumByRecursion(100);
            Console.WriteLine($"sum = {sum03}");
            // Console.ReadLine();
        }
    }
    class calculator
    {
    
public int GetSumByFor(int num) { int sum = 0; for (int i = 0; i < num + 1; i++) { sum += i; } return sum; } public int GetSumByRecursion(int num) { if (num == 1) return num; else { return num + GetSumByRecursion(num - 1); } } public int GetSumByMath(int num) { int result = (1 + num) * num / 2; return result; } }

简单递归应用(汉诺塔)

 class Program
    {
        static void Main(string[] args)
        {
            HanoiTowerPro A = new HanoiTowerPro();
            ulong result = A.Han(64);
            Console.WriteLine("An=" + result);
        }
    }
    class HanoiTowerPro
    {
        public ulong Han(ulong x)
        {
            if(x==1)
            {
                return 1;

            }
            else
            {
                ulong result = 2 * Han(x - 1) + 1;
                return result;
            }
        }
    }

四、示例构造器(构造器的定义)

class Student
{
    public Student()
    {
        this.Stu_ID = "001";
        this.Stu_Name = "No NAME!";
    }

    public Student(string ID, string Name)
    {
        this.Stu_ID = ID;
        this.Stu_Name = Name;
    }

    public string Stu_ID;
    public string Stu_Name;
}

构造器的调用

class Program
    {
        static void Main(string[] args)
        {
            Student Stu1 = new Student();
            Console.WriteLine(Stu1.Stu_ID);
            Console.WriteLine(Stu1.Stu_Name);
            Console.WriteLine("======================");
            Student Stu2 = new Student("002", "Shixuan Liu");
            Console.WriteLine(Stu2.Stu_ID);
            Console.WriteLine(Stu2.Stu_Name);

        }
    }

五、方法的简单应用,以及方法嵌套(计算圆面积,圆柱体积,圆锥体积)

class Program
    {
        static void Main(string[] args)
        {
            Calculator Result = new Calculator();
            double FinalResult = Result.GetConeVolume(100, 10);
            Console.WriteLine(FinalResult);
        }
    }
    class Calculator
    {
        public double GetcircleArea(double r)
        {
            return Math.PI * r * r;
        }

        public double GetCylinderVolume(double r,double h)
        {
            return GetcircleArea(r) * h;
        }

        public double GetConeVolume(double r,double h)
        {
            return GetCylinderVolume(r, h) / 3;
        }
    }

 六、不安全的代码(C#使用C的语法)

  class Program
    {
        static void Main(string[] args)
        {
            unsafe
            {
                Student stu;// = new Student();
                stu.Age = 18;
                stu.Score = 99;
                Student* pstu = &stu;
                pstu->Score = 100;
                (*pstu).Score = 1000;
                Console.WriteLine(stu.Score);
            }
        }

        struct Student
        {
           public int Age;
           //public string Name;
           public int Score;

        }
    }

七、操作符即为函数方法的简记法

    class Program
    {
        static void Main(string[] args)
        {
            Person Father = new Person();
            Person Mother = new Person();
            Father.Name = "Xiong";
            Mother.Name = "Liu";
            List<Person> descendant = Father+Mother;//可以变更为Father + Mother
            foreach (var p in descendant)
            {
                Console.WriteLine(p.Name);
            }
        }
    }

    class Person
    {
        public string Name;
        public static List<Person> operator +(Person p1, Person p2) //可以变更为 operator +
        {
            List<Person> people = new List<Person>();
            people.Add(p1);
            people.Add(p2);
            for (int i = 0; i < 5; i++)
            {
                Person child = new Person();
                child.Name = p1.Name + "&" + p2.Name + "'s child" + (i + 1);
                people.Add(child);
            }

            return people;
        }
    }

 

八、sizeof关键字的使用 转载(https://www.cnblogs.com/darrenji/p/3976029.html

在C#中,sizeof用来计算类型的大小,单位是字节。有这样的一个类:

    public class MyUglyClass
    {
        public char myChar1;
        public int myInt;
        public char myChar2;
    }

 

在客户端,试图使用sizeof计算该类型的大小。

    class Program
    {
        static void Main(string[] args)
        {
            MyUglyClass m = new MyUglyClass();
            m.myChar1 = 'd';
            m.myInt = 25;
            m.myChar2 = 'a';

            Console.WriteLine(sizeof(MyUglyClass));
        }
    }

运行,报错:
12

○ 第一个报错说明要使用sizeof,必须使用关键字unsafe
○ 第二个报错说明sizeof对运行时变量无效,只能针对编译器变量统计其大小

 

把类改成struct值类型。

    public struct MyUglyClass
    {
        public char myChar1;
        public int myInt;
        public char myChar2;
    }

 

客户端改成如下:

    class Program
    {
        static void Main(string[] args)
        {
            MyUglyClass m = new MyUglyClass();
            m.myChar1 = 'd';
            m.myInt = 25;
            m.myChar2 = 'a';
            unsafe
            {
                Console.WriteLine(sizeof(MyUglyClass));
            }
            
        }
    }

运行,继续报错:”不安全代码只会在使用 /unsafe 编译的情况下出现”。
解决方法是:右键项目→属性→生成→勾选”允许不安全代码”→保存

再次运行,结果:12

 

问题又来了,在MyUglyClass这个值类型结构中,char类型16位,相当于2个字节,int类型32位,相当于4个字节。MyUglyClass类型大小=2+2+4=8个字节,应该是8个字节才对!怎么会是12个字节呢?

 

这就涉及到栈的对齐和填充了。就拿上面的例子来说:原本,栈上有int类型的变量占4个字节,2个char类型的变量分别占2个字节,当栈上的这些变量排列之后,栈还要进行对齐排列,即所有较小字节的变量向最大字节的变量看齐,并且填充空位。

13

红叉部分是为了对齐而填充补上的。

 

如果想忽略为了对齐而填充补上的部分,可以使用[StructLayout]特性。

    [StructLayout(LayoutKind.Auto)]
    public struct MyUglyClass
    {
        public char myChar1;
        public int myInt;
        public char myChar2;
    }

再次运行,结果:8

总结:sizeof只适用于值类型,并且需要在unsafe上下文环境中使用。

九、C#数据类型所占用的字节数

bool -> System.Boolean (布尔型,其值为 true 或者 false)

byte -> System.Byte (字节型,占 1 字节,表示 8 位正整数,范围 0 ~ 255)

sbyte -> System.SByte (带符号字节型,占 1 字节,表示 8 位整数,范围 -128 ~ 127)

char -> System.Char (字符型,占有两个字节,表示 1 个 Unicode 字符)

short -> System.Int16 (短整型,占 2 字节,表示 16 位整数,范围 -32,768 ~ 32,767)

ushort -> System.UInt16 (无符号短整型,占 2 字节,表示 16 位正整数,范围 0 ~ 65,535)

uint -> System.UInt32 (无符号整型,占 4 字节,表示 32 位正整数,范围 0 ~ 4,294,967,295)

int -> System.Int32 (整型,占 4 字节,表示 32 位整数,范围 -2,147,483,648 到 2,147,483,647)

float -> System.Single (单精度浮点型,占 4 个字节)

ulong -> System.UInt64 (无符号长整型,占 8 字节,表示 64 位正整数,范围 0 ~ 大约 10 的 20 次方)

long -> System.Int64 (长整型,占 8 字节,表示 64 位整数,范围大约 -(10 的 19) 次方 到 10 的 19 次方)

double -> System.Double (双精度浮点型,占8 个字节)

十、类型转换(待补充)

class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine(ushort.MaxValue);

            Stone stone = new Stone();
            Monkey Wukongsun = new Monkey();
            stone.Age = 5000;
            Wukongsun = (Monkey)stone;
            Console.WriteLine(Wukongsun.Age);
        }
    }

    class Stone
    {
        public int Age;

        public static explicit operator Monkey(Stone stone) //implicit就是隐性转换操作符。
        {
            Monkey A = new Monkey();
            A.Age = stone.Age / 500;
            return A;
        }
    }

    class Monkey
    {
        public int Age;
    }

十一、使用Checked关键字来检查溢出,可以防止在运算中由于溢出而得到错误的运算结果。

int temp = int.MaxValue;
try
{
    int a = checked(temp * 2);
    Console.WriteLine(a);
}
catch (OverflowException)
{
Console.WriteLine("溢出了,要处理哟");
}

注意:普通运算符(+,-,*,/)都会导致溢出,但是位移运算符无法检查出溢出(<<,>>)

class Program
    {
        static void Main(string[] args)
        {
            //用户输入数字以及位移量
            Console.WriteLine("请输入数字(0-2147483648):");
            int IntNum10 = Convert.ToInt32(Console.ReadLine(), 10);
            Console.WriteLine("请输入位移量:");
            int IntMoveNum10 = Convert.ToInt32(Console.ReadLine(), 10);

            String BinStrNum2 = Convert.ToString(IntNum10, 2).PadLeft(32, '0');
            Console.WriteLine(BinStrNum2);


            try
            {
                int FinalNum = checked(IntNum10 << IntMoveNum10);
                String BinFinalNum = Convert.ToString(FinalNum, 2).PadLeft(32, '0');
                Console.WriteLine(BinFinalNum);
                Console.WriteLine(FinalNum);
                int a = checked((byte)FinalNum);
            }
            catch(OverflowException)
            {
                Console.WriteLine("溢出了");
            }

        }
    }

十二、Is,As关键字

转载https://www.cnblogs.com/haiyang1985/archive/2009/03/12/1410023.html

1)对于Is关键字,is检查对象是否与给定类型兼容。

如果所提供的表达式非空,并且所提供的对象可以强制转换为所提供的类型而不会导致引发异常,则 is 表达式的计算结果将是 true。

如果已知表达式将始终是 true 或始终是 false,则 is 关键字将导致编译时警告,但是,通常在运行时才计算类型兼容性。

不能重载 is 运算符。

请注意,is 运算符只考虑引用转换、装箱转换和取消装箱转换。不考虑其他转换,如用户定义的转换。

在 is 运算符的左侧不允许使用匿名方法。lambda 表达式属于例外。

class MyQuickSort
{
    static void Main(string[] args)
    {
        class2 c2 = new class2();

        if (c2 is class1)
        {
            Console.WriteLine("Yes");
        }
        else
        {
            Console.WriteLine("No");
        }

        Console.ReadLine();
    }
}

class class1
{
    public override string ToString()
    {
        return "";
    }
}

class class2:class1
{

}

结果为“YES”。

2)对于As关键字,As检查对象是否与给定类型兼容。

as 运算符用于在兼容的引用类型之间执行某些类型的转换。

对于基本类型如下(不能用于值类型):

static void Main(string[] args)
{
    object[] obj = new object[3];
    obj[0] = new class1();
    obj[1] = "hello";
    obj[2] = 10;

    for (int i = 0; i < obj.Length; i++)
    {
        string s = obj[i] as string;
        if (s != null)
        {
            Console.WriteLine(s);
        }
        else
        {
            Console.WriteLine("not a string");
        }
    }

    Console.ReadLine();
}

结果:

not a string

hello

not a string

对于继承类如下:

class Base
{
    public override string ToString()
    {
        return "Base";
    }
}
class Derived : Base
{ }

class Program
{
    static void Main()
    {

        Derived d = new Derived();

        Base b = d as Base;
        if (b != null)
        {
            Console.WriteLine(b.ToString());
        }

    }
}

对于继承类,允许把子类转换成父类,但是不可以把父类转换成子类,不同类之间,值类型不可转换。

十三、使用Try Catch关键字抓取程序中的异常,避免程序由于异常而中断,并且通过自定义的错误信息快捷判断错误内容。

 1 class TryStatement  2  {  3 static void Main(string[] args)  4  {  5 Console.WriteLine("请输入第一个数字:");  6 string x = Console.ReadLine();  7  8 Console.WriteLine("请输入第二个数字:");  9 string y = Console.ReadLine(); 10 11 Cacurlate Sum = new Cacurlate(); 12 int OverError = 0; 13 try 14  { 15 OverError = Sum.Add(x, y); 16  } 17 catch (FormatException) 18  { 19 Console.WriteLine("Your Argument(s) is not number!"); 20  } 21 22 Console.WriteLine("{0}+{1}={2}",x,y, OverError); 23 24  } 25 26 27  } 28 29 class Cacurlate 30  { 31 public int Add(string x, string y) 32  { 33 int a = 0; 34 int b = 0; 35 bool hasError = false; 36 37 try 38  { 39 a = int.Parse(x); 40 b = int.Parse(y); 41  } 42 catch(ArgumentNullException) 43  { 44 Console.WriteLine("Your argument(s) is null!"); 45 hasError = true; 46  } 47 catch(OverflowException) 48  { 49 Console.WriteLine("Your Argument(s) is out of range!"); 50 hasError = true; 51  } 52 catch(FormatException) 53  { 54 //Console.WriteLine("Your Argument(s) is not number!"); 55 // hasError = true; 56 throw; 57 58  } 59 finally 60  { 61 //一般我们在Finally子句中,会写以下两种情况: 62 //1.申请系统资源(打开数据库的连接),这样不论代码是否出现异常,我们都可以执行关闭数据库的语句 63 //2.会写程序的执行记录。 64 switch (hasError) 65  { 66 case true: Console.WriteLine("输入有误,请注意");break; 67 case false: Console.WriteLine("Done!");break; 68 default: Console.WriteLine("FFF!");break; 69  } 70  } 71 72 int result = a + b; 73 74 return result; 75  } 76 }

十四、拓展方法的使用

注意点:

1)需要在一个静态类中使用静态方法为原类型进行拓展。

2)第一个参数需要使用this关键字进行修饰。

3)第一个参数不能使用其他修饰符(ref,out等)。

4)调用时,可以使用第一个参数的类型的对象进行调用,同时会将该对象作为第一个参数在函数中开辟内存。

 class Program { static void Main(string[] args) { Console.WriteLine("Hello World!"); string A = "abc"; string B = "def"; A.Add(B,ref A); Console.WriteLine(A); } } public static class Intutility { public static void Add(this string a,string b,ref string c) { c = a + b; } }

十五、泛型*(定义一个泛型的数组工具类)

 1 class Program  2  {  3 static void Main(string[] args)  4  {  5  6  }  7  8 /// <summary>  9 /// 在泛型数组array中逐一查找元素t2,若存在则将其返回  10 /// </summary>  11 /// <typeparam name="T">类型</typeparam>  12 /// <param name="contition">判断条件,循环中判断这一数值是否相等</param>  13 /// <param name="array">被查找的数组</param>  14 /// <param name="t2">被查找的元素</param>  15 /// <returns></returns>  16 public static T Find<T>(Func<T,T,bool> contition,T[] array,T t2)  17  {  18  19 for (int i = 0; i < array.Length; i++)  20  {  21 if (contition(array[i], t2)) return array[i];  22  }  23  24 return default(T);  25  }  26  27 public static T[] FindAll<T>(Func<T,bool> condition,T[] array)  28  {  29 List<T> list = new List<T>();  30 for (int i = 0; i < array.Length; i++)  31  {  32 if (condition(array[i])) list.Add(array[i]);  33  }  34  35 return list.ToArray();  36  }  37  38 public static T[] BubSortUp<T>(Func<T,T,bool> condition, T[] array) where T:struct  39  {  40 bool state = false;  41 int index = 0;  42 do  43  {  44 state = false;  45 for (int i = 0; i < array.Length - 1 - index++; i++)  46  {  47 if (condition(array[i], array[i + 1]))  48  {  49 Swap(ref array[i],ref array[i + 1]);  50 state = true;  51  }  52  }  53 } while (state || index < array.Length-1);  54  55 return array;  56  }  57  58  59 public static T[] BubSortDown<T>(Func<T, T, bool> condition, T[] array) where T : struct  60  {  61 bool state = false;  62 int index = 0;  63 do  64  {  65 state = false;  66 for (int i = array.Length - 1 - index++; i > 0; i--)  67  {  68 if (condition(array[i], array[i - 1]))  69  {  70 Swap(ref array[i], ref array[i - 1]);  71 state = true;  72  }  73  }  74 } while (state || index < array.Length - 1);  75  76 return array;  77  }  78  79 public static T GetMax<T>(Func<T,T,bool> condition,T[] array)  80  {  81 T max = array[0];  82 foreach (var item in array)  83  {  84 if(condition(max,item))  85  {  86 max = item;  87  }  88  }  89 return max;  90  }  91  92 public static T GetMin<T>(Func<T, T, bool> condition, T[] array)  93  {  94 T min = array[0];  95 foreach (var item in array)  96  {  97 if (condition(min, item))  98  {  99 min = item; 100  } 101  } 102 return min; 103 104  } 105 106 public static List<Q> SelectAll<T,Q>(Func<T,Q> condition,T[] array) 107  { 108 List<Q> resultArr = new List<Q>(array.Length); 109 for (int i = 0; i < array.Length; i++) 110  { 111  resultArr.Add(condition(array[i])); 112 113  } 114 return resultArr; 115  } 116 117 public T BinarySeach<T>(Func<T,T,int> condition,T[] array,T t2,int upLim,int lowerLim) 118  { 119 if (upLim < lowerLim) return default(T); 120 121 int midIndex = (lowerLim + upLim) / 2; 122 T mid = array[midIndex]; 123 if (condition(mid, t2) == 0) return mid; 124 else if (condition(mid, t2) == -1) return BinarySeach<T>(condition, array,t2, upLim, midIndex+1); 125 else if (condition(mid, t2) == 1) return BinarySeach<T>(condition, array, t2, midIndex - 1, lowerLim); 126 else return default(T); 127  } 128 129 private static void Swap<T>(ref T t1,ref T t2) where T : struct 130  { 131  T temp; 132 temp = t1; 133 t1 = t2; 134 t2 = temp; 135  } 136 137 /* 自定义泛型的约束 138  * T :struct 限定T类型只能为值类型 139  * T : class 限定Q类型为引用类型 140  * T :ICloneable 只能是ICloneable的子类; 141  T :Person 限定K类型只能为 142  Person或者Person的子类 143  * T : class,new() 限定w类型是引用类型 144  * 并且使用了无参构造函数 145 */ 146 }

十五、委托详解

委托是C/C++语言中函数指针的升级版,可以用来存储函数(方法)的地址,从而通过函数(方法)的地址进行间接的调用。

1)方法直接调用的示例

 1 class Program  2  {  3 static void Main(string[] args)  4  {  5 Teacher teacher01 = new Teacher();  6  teacher01.Rings(state.Playing);  7  teacher01.Rings(state.Sleeping);  8  teacher01.Rings(state.Talking);  9  } 10  } 11 enum state 12  { 13  Playing, 14  Sleeping, 15  Talking 16  } 17 class Teacher 18  { 19 Student stu01 = new Student(); 20 public void Rings(state s) 21  { 22 switch (s) 23  { 24 case state.Playing: 25  stu01.Playing(); 26 break; 27 case state.Sleeping: 28  stu01.Sleeping(); 29 break; 30 case state.Talking: 31  stu01.Talking(); 32 break; 33  } 34  } 35  } 36 class Student 37  { 38 public void Playing() 39  { 40 Console.WriteLine("玩!"); 41  } 42 public void Sleeping() 43  { 44 Console.WriteLine("睡!"); 45  } 46 public void Talking() 47  { 48 Console.WriteLine("聊!"); 49  } 50 }

方法中通过函数方法名直接调用Student类中的方法成员。

2)间接调用

 1 //定义委托(本质是一种类)(声明的时候要求与封装的函数的签名相兼容)  2 delegate void Dele();  3 class Program  4  {  5 static void Main(string[] args)  6  {  7 Dele dele01 = new Dele(Student.Playing);  8 Dele dele02 = Student.Sleeping;  9 Dele dele03 = new Dele(Student.Talking); 10 11 Teacher teacher01 = new Teacher(); 12  teacher01.Rings(dele01); 13  dele02.Invoke(); 14  dele03(); 15  } 16 //定义一个老师类,一个学生类,主调函数通过老师类的方法Rings通知,调用学生的方法。 17 class Teacher 18  { 19 Student stu01 = new Student(); 20 public void Rings(Dele dele) 21  { 22  dele(); 23  } 24  } 25 class Student 26  { 27 public static void Playing() 28  { 29 Console.WriteLine("玩!"); 30  } 31 public static void Sleeping() 32  { 33 Console.WriteLine("睡!"); 34  } 35 public static void Talking() 36  { 37 Console.WriteLine("聊!"); 38  } 39  } 40 }

C#中常用的已经定义好的委托类型有(Action/Func<>).

委托的一般使用,包括模板方法、回调方法。

两者主要区别于不同的应用场景中,在不同的场景中会采用不同的调用方法。

以下示例用于理解:

1)模板方法:在方法中,通过外部方法获得返回值结果,通常这个结果是有多种可能性的,常位于代码中段,赋予了动态调用方法的方式。

2)回调方法:同时在方法中会根据方法的执行情况,根据一定的逻辑进行判断是否要进行回调,如需要回调,会将方法中的执行结果作为参数去调用外部的方法,通常用于向方法体外部(其他类)传递方法执行后的部分变量的信息。

 1 class Program  2  {  3 static void Main(string[] args)  4  {  5 WrapFactory myWrapFac = new WrapFactory();  6 ProductFactory myProductFac = new ProductFactory();  7 //通过模板方法,动态进行方法调用,相比直接调用减少了方法体中的判断,加强复用,使用灵活,但是增加了代码的耦合度。  8  myWrapFac.Wrapproduct(myProductFac.MakePizza, ProductLog.RecordLog01);  9  myWrapFac.Wrapproduct(myProductFac.MakeToycar, ProductLog.RecordLog02); 10 11  } 12  } 13 14 class Product 15  { 16 public string Name { get; set; } 17 public float Price { get; set; } 18  } 19 20 class Box 21  { 22 public Product Pro { get; set; } 23  } 24 25 class WrapFactory 26  { 27 //通过模板方法、回调方法使用委托 28 public Box Wrapproduct(Func<Product> getProduct,Action<Product> action) 29  { 30 Box box = new Box(); 31 box.Pro = getProduct.Invoke();//典型模板方法 32 if (box.Pro.Price > 50) 33 action.Invoke(box.Pro);//典型回调方法 34 return box; 35  } 36  } 37 38 class ProductLog 39  { 40 public static void RecordLog01(Product product) 41  { 42 Console.WriteLine("RecordLog01_"+product.Name + "_" + DateTime.UtcNow + product.Price); 43  } 44 public static void RecordLog02(Product product) 45  { 46 Console.WriteLine("RecordLog02_" + product.Name + "_" + DateTime.UtcNow + product.Price); 47  } 48  } 49 50 class ProductFactory 51  { 52 public Product MakePizza() 53  { 54 Product proPizza = new Product(); 55 proPizza.Name = "pizza01"; 56 proPizza.Price = 12; 57 return proPizza; 58  } 59 public Product MakeToycar() 60  { 61 Product proToycar = new Product(); 62 proToycar.Name = "pizza01"; 63 proToycar.Price = 100; 64 return proToycar; 65  } 66 }

委托的高级应用:

<span role="heading" aria-level="2">C#代码集

 

 使用接口取代对委托的使用,对上述代码进行重构:

 1 class Program  2  {  3 static void Main(string[] args)  4  {  5 WrapFactory myWrapFac = new WrapFactory();  6 IProductFactory pizzaFactory = new PizzaFactory();  7 IProductFactory toycarFactory = new ToyCarFactory();  8 //通过模板方法,动态进行方法调用,相比直接调用减少了方法体中的判断,加强复用,使用灵活,但是增加了代码的耦合度。  9  myWrapFac.Wrapproduct(pizzaFactory, ProductLog.RecordLog01); 10  myWrapFac.Wrapproduct(toycarFactory, ProductLog.RecordLog02); 11 12  } 13  } 14 15 public interface IProductFactory 16  { 17 public Product MakeProduct(); 18  } 19 20 class PizzaFactory:IProductFactory 21  { 22 public Product MakeProduct() 23  { 24 Product proPizza = new Product(); 25 proPizza.Name = "pizza01"; 26 proPizza.Price = 12; 27 return proPizza; 28  } 29  } 30 31 class ToyCarFactory: IProductFactory 32  { 33 public Product MakeProduct() 34  { 35 Product proToycar = new Product(); 36 proToycar.Name = "pizza01"; 37 proToycar.Price = 100; 38 return proToycar; 39  } 40  } 41 42 public class Product 43  { 44 public string Name { get; set; } 45 public float Price { get; set; } 46  } 47 48 class Box 49  { 50 public Product Pro { get; set; } 51  } 52 53 class WrapFactory 54  { 55 //通过模板方法、回调方法使用委托 56 public Box Wrapproduct(IProductFactory Ipro,Action<Product> action) 57  { 58 Box box = new Box(); 59 box.Pro = Ipro.MakeProduct();//典型模板方法 60 if (box.Pro.Price > 50) 61 action.Invoke(box.Pro);//典型回调方法 62 return box; 63  } 64  } 65 66 class ProductLog 67  { 68 public static void RecordLog01(Product product) 69  { 70 Console.WriteLine("RecordLog01_"+product.Name + "_" + DateTime.UtcNow + product.Price); 71  } 72 public static void RecordLog02(Product product) 73  { 74 Console.WriteLine("RecordLog02_" + product.Name + "_" + DateTime.UtcNow + product.Price); 75  } 76 }

委托与事件

声明时,使用event关键字,定义城堡类,其中声明委托与事件。

 1 public delegate void EventDele01();  2  3 class MainCity  4  {  5 //委托的声明  6 public delegate void Dele();  7 public Dele dele;  8 //事件的声明  9 public event Action EventDele; 10 public event EventDele01 eventDele01; 11 12 public float Hp; 13 public float maxHp; 14 public void Damage(float decrease) 15  { 16 this.Hp -= decrease; 17 //委托的调用 18  dele(); 19 //事件的调用 20  EventDele(); 21  } 22 }

定义士兵类,城墙类,警报类

 1 class Enclosure  2  {  3 public static void EnclosureUppon()  4  {  5 Console.WriteLine("加固城墙!");  6  }  7  }  8 class Alarm  9  { 10 public static void Rings() 11  { 12 Console.WriteLine("警报响起!"); 13  } 14  } 15 class Solder 16  { 17 public static void LevelUp() 18  { 19 Console.WriteLine("我升级了!"); 20  } 21 22 }

假设,在主调函数中,一个城堡对象在在受伤后,会调用上述类中的方法,那么在上述的MainCity类中的Damage方法中已经进行了调用,而在主调函数中,我们只需要将委托以及事件进行注册即可。

 1 static void Main(string[] args)  2  {  3  4 MainCity main = new MainCity() { Hp = 100, maxHp = 100 };  5 //《委托的应用》  6 //委托可以在声明委托的外部类中进行“注册”,无论该委托的声明是否在该命名空间下。  7 main.dele = Alarm.Rings;  8 main.dele += Enclosure.EnclosureUppon;  9 main.dele += Solder.LevelUp; 10 //委托可以在声明委托的外部类中进行“撤销”,无论该委托的声明是否在该命名空间下。 11 main.dele -= Solder.LevelUp; 12 //同时委托可以在声明委托的外部类中进行“清空” 13 main.dele = null; 14 //同时委托可以在声明委托的外部类中进行“调用” 15  main.dele(); 16 17 //《事件的应用》 18 //事件可以在声明事件的外部类中进行“注册”,无论该事件的声明是否在该命名空间下。 19 main.EventDele += Alarm.Rings; 20 main.EventDele += Enclosure.EnclosureUppon; 21 main.EventDele += Solder.LevelUp; 22 //事件可以在声明事件的外部类中进行“撤销”,无论该事件的声明是否在该命名空间下。 23 main.EventDele -= Solder.LevelUp; 24 //事件链(委托链)不能在类的外部被清空。(不同点) 25 main.EventDele = null;//代码报错 26 //事件链(委托链)不能在类的外部进行“调用”(不同点) 27  main.EventDele();//代码报错 28 //如果需要调用的话,需要在声明委托的类中进行调用,在Damage方法中封装了事件的调用。 29 //这也是封装的思想,事件本身是MainCity类中自发产生的效果,不应当由外部进行调用。 30 main.Damage(10); 31 32 33 34 /*优劣势:通过对委托的封装,形成事件,相比之下有如下几点优劣势 35  /* 缺点:1. 绑定多个方法,但是运算符不一致 = += -= 36  * 当你绑定多个方法的时候第一个用=,后面用+= 37  * 2.对外部提供了清空以及调用的权限,违背了封装的思想 38  * --其他类可以直接调用委托; 39  * --其他的类可以直接清空委托链 40  * 41  * 事件:1.运算符一致,+=、 -= 42  * 2.只能在其他类进行绑定和解除事件 43  * --其他类不能直接调用事件 44  * --其他类不能直接请事件中的委托链 45 */ 46 }

 

C#基础代码Practice

01.根据命令窗口输入的数字以及运算符,进行判断并且运算。

class Program { static void Main(string[] args) { //获取数据 Console.WriteLine("请以如下格式给出两个数字及一个运算符(a,b,*):"); string Count = Console.ReadLine(); //逻辑处理 string strNum01 = char.ToString(Count[0]); int Num01 = int.Parse(strNum01); string strNum02 = char.ToString(Count[2]); int Num02 = int.Parse(strNum02); string Op = char.ToString(Count[4]); int result = 0; if(Op == "+") { result += Num01 + Num02; Console.WriteLine(result); } else if (Op == "-") { result += Num01 - Num02; Console.WriteLine(result); } else if(Op == "*") { result += Num01 * Num02; Console.WriteLine(result); } else if(Op == "/") { result += Num01 / Num02; Console.WriteLine(result); } else { Console.WriteLine("输入无效"); } }

02.将一个数字的所有位数相加

 1 class Program  2  {  3 static void Main(string[] args)  4  {  5 Console.WriteLine("请输入一个四位数数字:");  6 string BeginNum = Console.ReadLine();  7  8 string c1 = Convert.ToString(BeginNum[0]);  9 string c2 = Convert.ToString(BeginNum[1]); 10 string c3 = Convert.ToString(BeginNum[2]); 11 string c4 = Convert.ToString(BeginNum[3]); 12 13 int Intc1 = int.Parse(c1); 14 int Intc2 = int.Parse(c2); 15 int Intc3 = int.Parse(c3); 16 int Intc4 = int.Parse(c4); 17 18 Console.WriteLine(Intc1+ Intc2 + Intc3 + Intc4 ); 19  } 20 }

03.IF的逻辑判断

 class Program { static void Main(string[] args) { //获取数据 Console.WriteLine("请输入一个数字(0-100):"); string StrGrade = Console.ReadLine(); //逻辑处理 int Grade = int.Parse(StrGrade); string result; if(90 <= Grade && Grade <= 100) { result = "优秀"; Console.WriteLine(result); } else if (80 <= Grade && Grade < 90) { result = "良好"; Console.WriteLine(result); } else if (60 <= Grade && Grade < 80) { result = "及格"; Console.WriteLine(result); } else if (0 <= Grade && Grade < 60) { result = "不及格"; Console.WriteLine(result); } else { Console.WriteLine("输入无效"); } } }

04.根据年份、月份,判断该月所包含的天数。

class Program { static void Main(string[] args) { //数据输入 Console.WriteLine("请输入年份:"); string Year = Console.ReadLine(); int IntYear = int.Parse(Year); Console.WriteLine("请输入月份:"); string Month = Console.ReadLine(); string result1; string result2; if (IntYear > 9999 || IntYear<=0) { result1 = "请输入有效的年份!"; Console.WriteLine(result1); } else { switch(Month) { case "1": result2 = "31"; break; case "2": if (IntYear % 4 == 0 && IntYear % 100 != 0) result2 = "29"; else if (IntYear % 400 == 0) result2 = "29"; else result2 = "28";break; case "3": result2 = "31"; break; case "4": result2 = "30"; break; case "5": result2 = "31"; break; case "6": result2 = "30"; break; case "7": result2 = "31"; break; case "8": result2 = "31"; break; case "9": result2 = "30"; break; case "10": result2 = "31"; break; case "11": result2 = "30"; break; case "12": result2 = "31"; break; default: result2 = "请输入1-12!"; break; } Console.WriteLine(result2); } } }

05.根据输入年份,打印日历

 1 class Program  2  {  3 static void Main(string[] args)  4  {  5 Console.WriteLine("请输入一个年份:");  6 int year = int.Parse(Console.ReadLine());  7  8 for (int month = 1; month <= 12; month++)  9  {  10  MonthCalendar(year, month);  11  }  12  13  }  14  15 /// <summary>  16 /// 打印月历  17 /// </summary>  18 /// <param name="year"></param>  19 /// <param name="month"></param>  20 private static void MonthCalendar(int year,int month)  21  {  22 Console.WriteLine("{0} 年 {1} 月", year, month);  23 Console.WriteLine("日\t一\t二\t三\t四\t五\t六");  24  25  MonthCalendarFDay(year, month);  26  MonthCalendarDays(year, month);  27  28  }  29  30 /// <summary>  31 /// 用于将每月第一天放在正确的星期数的位置  32 /// </summary>  33 /// <param name="year">年份</param>  34 /// <param name="month">月份</param>  35 private static void MonthCalendarFDay(int year, int month)  36  {  37 int FirstDay = GetWeekByYMD(year, month, 1);  38 for (int i = 0; i < FirstDay; i++)  39  {  40 Console.Write("\t");  41  }  42  }  43  44 /// <summary>  45 /// 用于打印每月的日期  46 /// </summary>  47 /// <param name="year"></param>  48 /// <param name="month"></param>  49 private static void MonthCalendarDays(int year, int month)  50  {  51 int DayNum = GetDayNum(year, month);  52  53 for (int Day = 1; Day <= DayNum; Day++)  54  {  55 Console.Write("{0}",Day);  56 int WeekOfDay = GetWeekByYMD(year, month, Day);  57 switch (WeekOfDay)  58  {  59 case 6:  60 Console.Write("\n"); break;  61 default:  62 Console.Write("\t"); break;  63  }  64  }  65  66 Console.WriteLine("\n");  67  }  68  69 /// <summary>  70 /// 提供int类型的年、月、日的变量,返回int类型的星期数  71 /// </summary>  72 /// <param name="year">年份</param>  73 /// <param name="month">月份</param>  74 /// <param name="day">日期</param>  75 /// <returns></returns>  76 private static int GetWeekByYMD(int year, int month, int day)  77  {  78 DateTime dt = new DateTime(year,month,day);  79 int result = (int)dt.DayOfWeek;  80 return result;  81  }  82  83 /// <summary>  84 /// 获取int年份、月份的天数  85 /// </summary>  86 /// <param name="year">年份</param>  87 /// <param name="month">月份</param>  88 /// <returns></returns>  89 private static int GetDayNum(int year, int month)  90  {  91 if (month < 1 && month > 12) return 0;  92  93 int result;  94 switch (month)  95  {  96 case 2:  97 result = ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) ? 29 : 28;  98 break;  99 case 4: 100 case 6: 101 case 9: 102 case 11: 103 result = 30;break; 104 default: 105 result = 31;break; 106  } 107 return result; 108  } 109 110 }

 06.3+6+9+…+99

 class Program { static void Main(string[] args) { int Sum = 0; for (int i = 1; i < 101; i++) { if (i % 3 == 0 && i > 2) Sum += i; else continue; } Console.WriteLine(Sum); } }

07.输入不同类型的时间,根据用户指定的类型的时间转换成秒数

 1 class Program  2  {  3 static void Main(string[] args)  4  {  5 Console.WriteLine("请输入您需要转换的时间类型(day or hour or min):");  6 string type = Console.ReadLine();  7 string Lowtype = type.ToLower();  8  9 Console.WriteLine("请输入数量:"); 10 int Num = 0; 11 12 try 13  { 14 Num = int.Parse(Console.ReadLine()); 15  } 16 catch 17  { 18 Console.WriteLine("输入数字太大或太小!"); 19  } 20 21 try 22  { 23 switch (Lowtype) 24  { 25 26 case "day": 27 Console.WriteLine(MtoSec(HtoMin(DtoHour(Num)))); break; 28 case "hour": 29 Console.WriteLine(MtoSec(HtoMin(Num))); break; 30 case "min": 31 Console.WriteLine(MtoSec(Num)); break; 32 case "secound": 33 Console.WriteLine(); break; 34 35 default: 36 Console.WriteLine("类型输入有误");break; 37  } 38  } 39 catch 40  { 41 Console.WriteLine("输入数字太大!"); 42  } 43  } 44 45 46 47 private static int MtoSec(int Min) 48  { 49 int result = 60 * Min; 50 return result; 51  } 52 53 private static int HtoMin(int hour) 54  { 55 int result = 60 * hour; 56 return result; 57  } 58 59 private static int DtoHour(int Day) 60  { 61 int result = 24 * Day; 62 return result; 63  } 64 65 private enum Playerimput 66  { 67  day, 68  hour, 69  min, 70  secound, 71  } 72 }

08.猜数字游戏

class Program { static void Main(string[] args) { Console.WriteLine("请输入一个数字(1-100):"); int ImputNum; Random random = new Random(); int RandomNum = random.Next(1, 101); int i = 0; do { ImputNum = int.Parse(Console.ReadLine()); i++; if (ImputNum > RandomNum) Console.WriteLine("您猜测的数字较大!"); else if (ImputNum < RandomNum) Console.WriteLine("您猜测的数字较小!"); else Console.WriteLine("您猜测的数字对了!总共猜测了{0}次",i); } while (ImputNum != RandomNum); } }

09.一个小球从100m高空下落,每次落地后弹起,当小球离地面高度小于0.01m的时候不会再次弹起,请问小球经历了多少次碰地,以及小球运动的总路程。

 class Program { static void Main(string[] args) { float BallHeight = 100; int i = 0; float Sum = 100; while (BallHeight >= 0.01f) { i++; BallHeight /= 2; if (BallHeight >= 0.01f) Sum += BallHeight * 2; Console.WriteLine("第{0}次弹起{1}距离。",i,BallHeight); Console.WriteLine(Sum); } Console.WriteLine(BallHeight); Console.WriteLine("总共经过{0}次落地",i); Console.WriteLine("总共经过{0}米",Sum); } }

<span role="heading" aria-level="2">C#代码集

 

10.数组的使用,以及语法,以及常用的API函数*(待补充)

11.通过递归以及循环制作一个用于保存学生成绩的程序:

class Program { //递归方法。 static void Main(string[] args) { Console.WriteLine("请输入学生总数:"); int Num = int.Parse(Console.ReadLine()); float[] Grade = new float[Num]; Recursion(Num); void Recursion(int x) { if (x < 1) return; else { Console.WriteLine("请输入第{0}个学生的成绩", x); Grade[x - 1] = float.Parse(Console.ReadLine()); if (Review(Grade[x - 1])) Recursion(x - 1); else { Console.WriteLine("输入有误,请重新输入."); Recursion(x); } } } foreach (var item in Grade) { Console.WriteLine( item.ToString()); } } //For循环 private static int[] GetGrade(int x) { int[] StuGrade = new int[x]; for (int i = 0; i < x;) { Console.WriteLine("请输入第{0}个学生的成绩", i + 1); StuGrade[i] = int.Parse(Console.ReadLine()); if (Review(StuGrade[i])) i++; else Console.WriteLine("输入有误"); } return StuGrade; } private static bool Review(float Grade) { return Grade <= 100 && Grade >= 0; }

 12.七色球程序

 1 class Program  2  {  3 static void Main(string[] args)  4  {  5 Console.WriteLine("这是模拟七色球的小游戏,规则如下:玩家从33个红球中抽取6个(1-33),并从16个蓝球中抽取一个(1-16),如果与开奖数字相等,那么可能获得不同的大奖");  6 Console.WriteLine("中奖号码为:");  7 int[] A = GetBallsByAuto();  8 foreach (var item in A)  9  {  10  Console.WriteLine(item);  11  }  12 int[] B = GetBallsByArty();  13  EqualBallsCount(A, B);  14  }  15  16 /// <summary>  17 /// 获奖情况  18 /// </summary>  19 /// <param name="A">获奖数字</param>  20 /// <param name="B">购买数字</param>  21 private static void EqualBallsCount(int[] A, int[] B)  22  {  23 int RedNum = 0;  24 int BlueNum = 0;  25 for (int i = 0; i < A.Length - 1; i++)  26  {  27 if (Array.IndexOf(A, B[i], 0, A.Length - 1) >= 0) RedNum++;  28  }  29  30 if (A[A.Length - 1] == B[B.Length - 1]) BlueNum++;  31  32 if (BlueNum == 1 && RedNum == 6) Console.WriteLine("恭喜你获得一等奖,奖金500万元");  33 else if (BlueNum == 0 && RedNum == 6) Console.WriteLine("恭喜你获得二等奖,奖金200万元");  34 else if (BlueNum == 1 && RedNum == 5) Console.WriteLine("恭喜你获得三等奖,奖金3000元");  35 else if ((BlueNum + RedNum) == 5) Console.WriteLine("恭喜你获得四等奖,奖金200元");  36 else if ((BlueNum + RedNum) == 4) Console.WriteLine("恭喜你获得五等奖,奖金10元");  37 else if ((BlueNum + RedNum) == 3) Console.WriteLine("恭喜你获得六等奖,奖金5元");  38 else if (BlueNum==1&&RedNum <= 1 && RedNum>=0) Console.WriteLine("恭喜你获得七等奖,奖金5");  39 else Console.WriteLine("再接再厉!");  40  }  41  42 /// <summary>  43 /// 获得一组随机七色球号码,并且进行排序  44 /// </summary>  45 /// <returns>数组</returns>  46 private static int[] GetBallsByAuto()  47  {  48 int[] RedBalls = new int[6];  49 Random RanNum = new Random();  50  51 //生成红球随机数,并且排序  52 for (int i = 0; i < RedBalls.Length;)  53  {  54 RedBalls[i] = RanNum.Next(1, 34);  55  56 if (!judgeMent(RedBalls, i)) i++;  57  }  58 Array.Sort(RedBalls);//排序  59  60 //声明返回数组,将红球随机数组复制在生成的数组的前6位  61 int[] Result = new int[7];  62 RedBalls.CopyTo(Result, 0);  63  64 //生成蓝球随机数  65 Result[6] = RanNum.Next(1, 17);  66 return Result;  67  }  68  69  70 /// <summary>  71 /// 根据提示在控制台输入七色球的值  72 /// </summary>  73 /// <returns></returns>  74 private static int[] GetBallsByArty()  75  {  76 int[] RedBalls = new int[6];  77 int[] Balls = new int[7];  78 //获取红球数字  79 for (int i = 0; i < RedBalls.Length;)  80  {  81  82 Console.WriteLine("请输入第{0}个红球号码", i + 1);  83 try  84  {  85 RedBalls[i] = int.Parse(Console.ReadLine());  86  }  87 catch  88  {  89 Console.WriteLine("输入不正确!");  90  }  91  92 if (RedBalls[i] > 33 || RedBalls[i] <= 0) Console.WriteLine("你输入的数字不正确");  93 else if (judgeMent(RedBalls, i)) Console.WriteLine("你输入的数字重复");  94 else i++;  95  96  }  97 //红球排序  98  Array.Sort(RedBalls);  99 100 //获取蓝球数字 101 Console.WriteLine("请输入篮球数字"); 102 Balls[Balls.Length - 1] = int.Parse(Console.ReadLine()); 103 if (Balls[Balls.Length - 1] > 16 || Balls[Balls.Length - 1] <= 0) Console.WriteLine("你输入的数字不正确"); 104 //拼接 105 RedBalls.CopyTo(Balls, 0); 106 107 return Balls; 108 109  } 110 111 /// <summary> 112 /// 判断指定数组中的指定索引位置的元素是否存在相同的值 113 /// </summary> 114 /// <param name="Array">数组</param> 115 /// <param name="x">指定数组的索引</param> 116 /// <returns></returns> 117 private static bool judgeMent(int[] Array, int x) 118  { 119 for (int i = 0; i < x; i++) 120  { 121 if (Array[x] == Array[i]) return true; 122  } 123 return false; 124  } 125 126 127 }

13.1-2+3-4+5….

 1 class Program  2  {  3 //1-2+3-4+5...  4 static void Main(string[] args)  5  {  6 Console.WriteLine(Fun(8));  7  }  8  9 private static int Fun(int x) 10  { 11 if (x == 1) return 1; 12 13 return ((int)Math.Pow(-1, x - 1)) * x + Fun(x - 1); 14 15  } 16 }

14.2048游戏数字逻辑

 1 class Program  2  {  3 static void Main(string[] args)  4  {  5 int[,] Board =  6  {  7 {2,2,2,0 },  8 {2,4,4,0 },  9 {2,0,4,4 },  10 {2,4,0,2 },  11  };  12  13  Move(Board, EnumDirection.down);  14  15 //Movedown(Board);  16 // MoveLeft(Board);  17  18 for (int i = 0; i < Board.GetLength(0); i++)  19  {  20 for (int j = 0; j < Board.GetLength(1); j++)  21  {  22 Console.Write(Board[i, j] + "\t");  23  }  24 Console.Write("\n");  25  }  26  27  }  28  29 //游戏初始化获得两个随机数  30 private static int[,] InitializeGame()  31  {  32 int[,] MainScreen = new int[4, 4];  33 //生成第一个随机数的随机索引位置  34 Random RandomIndex01 = new Random();  35 int lineIndex01 = RandomIndex01.Next(0, 4);  36 int ColumnIndex01 = RandomIndex01.Next(0, 4);  37  38 MainScreen[lineIndex01, ColumnIndex01] = 2;  39  40 //生成第二个随机数的随机索引位置  41 int lineIndex02;  42 int ColumnIndex02;  43 do  44  {  45 Random RandomIndex02 = new Random();  46 lineIndex02 = RandomIndex01.Next(0, 4);  47 ColumnIndex02 = RandomIndex01.Next(0, 4);  48 } while (lineIndex02 == lineIndex01 && ColumnIndex02 == ColumnIndex01);//用于校验第二个随机数的位置与第一个不同  49 MainScreen[lineIndex02, ColumnIndex02] = 2;  50  51 return MainScreen;  52  }  53  54 private static void Move(int[,] array, EnumDirection direction)  55  {  56 switch(direction)  57  {  58 case EnumDirection.up: Moveup(array);break;  59 case EnumDirection.down: Movedown(array); break;  60 case EnumDirection.left: MoveLeft(array); break;  61 case EnumDirection.right: MoveRight(array); break;  62 default:break;  63  64  }  65  }  66 private static void Movedown(int[,] array)  67  {  68 int[] lineArray = new int[array.GetLength(0)];  69 for (int i = 0; i < array.GetLength(1); i++)  70  {  71 for (int LineIndex = 0; LineIndex < array.GetLength(0); LineIndex++)  72  {  73 lineArray[array.GetLength(0)- 1 - LineIndex] = array[LineIndex, i];  74  }  75  Exchange(lineArray);  76  Combina(lineArray);  77  Exchange(lineArray);  78 for (int LineIndex = 0; LineIndex < array.GetLength(0); LineIndex++)  79  {  80 array[array.GetLength(0) - LineIndex - 1, i] = lineArray[LineIndex];  81  }  82  }  83  }  84 private static void Moveup(int[,] array)  85  {  86 int[] lineArray = new int[array.GetLength(0)];  87 for (int i = 0; i < array.GetLength(1); i++)  88  {  89 for (int LineIndex = 0; LineIndex < array.GetLength(0); LineIndex++)  90  {  91 lineArray[LineIndex] = array[LineIndex, i];  92  }  93  Exchange(lineArray);  94  Combina(lineArray);  95  Exchange(lineArray);  96 for (int LineIndex = 0; LineIndex < array.GetLength(0); LineIndex++)  97  {  98 array[LineIndex, i] = lineArray[LineIndex];  99  } 100  } 101  } 102 private static void MoveLeft(int[,] Array) 103  { 104 int[] ColumnArray = new int[Array.GetLength(1)]; 105 for (int LineIndex = 0; LineIndex < Array.GetLength(0); LineIndex++) 106  { 107 108 for (int i = 0; i < ColumnArray.Length; i++) 109  { 110 ColumnArray[i] = Array[LineIndex, i]; 111 112  } 113 while (Exchange(ColumnArray) || Combina(ColumnArray)) 114  { }; 115 116 for (int i = 0; i < ColumnArray.Length; i++) 117  { 118 Array[LineIndex, i] = ColumnArray[i]; 119  } 120 121  } 122 123  } 124 125 private static void MoveRight(int[,] Array) 126  { 127 128 int[] ColumnArray = new int[Array.GetLength(1)]; 129 for (int LineIndex = 0; LineIndex < Array.GetLength(0); LineIndex++) 130  { 131 132 for (int i = 0; i < ColumnArray.Length ; i++) 133  { 134 ColumnArray[i] = Array[LineIndex, ColumnArray.Length - 1 - i]; 135 136  } 137 while (Exchange(ColumnArray) || Combina(ColumnArray)) 138  { }; 139 140 for (int i = 0; i < ColumnArray.Length ; i++) 141  { 142 Array[LineIndex, ColumnArray.Length - 1 - i] = ColumnArray[i]; 143  } 144 145  } 146  } 147 private static bool Combina(int[] Array) 148  { 149 bool result = false; 150 for (int ColumnIndex = 0; ColumnIndex < Array.Length - 1; ColumnIndex++) 151  { 152 int CurrentIndex = ColumnIndex + 1; 153 if (Array[ColumnIndex] != 0 && Array[ColumnIndex] == Array[CurrentIndex]) 154  { 155 Array[ColumnIndex] += Array[CurrentIndex]; 156 Array[CurrentIndex] = 0; 157 result = true; 158  } 159 160  } 161 return result; 162  } 163 164 private static bool Exchange(int[] Array) 165  { 166 //Num = 0; 167 bool result = false; 168 for (int ColumnIndex = 0, CurrentIndex, ExchangeIndex = 0; ColumnIndex < Array.Length - 1; ColumnIndex++) 169  { 170 171 for (CurrentIndex = ColumnIndex + 1; CurrentIndex < Array.Length;)//若为0,则判断后续数组元素是否为0 172  { 173 if (Array[ColumnIndex] == 0 && Array[CurrentIndex] == 0) CurrentIndex++;//若后一位元素为0,则继续检索后续元素 174 else if (Array[ColumnIndex] == 0 && Array[CurrentIndex] != 0) 175  { 176 ExchangeIndex = CurrentIndex; 177 result = true; 178 break; 179  } 180 else break; 181  } 182 183 if (result)//判断数组中是否存在需要交换的数据,若是,则交换。 184  { 185 int Temp = Array[ColumnIndex]; 186 Array[ColumnIndex] = Array[ExchangeIndex]; 187 Array[ExchangeIndex] = Temp; 188  } 189 190 191 192 //while (Array[ColumnIndex] == 0 && CurrentIndex <= 3) 193 //{ 194 195 // if (Array[CurrentIndex] == 0) CurrentIndex++; 196 // else 197 // { 198 // int Temp = Array[ColumnIndex]; 199 // Array[ColumnIndex] = Array[CurrentIndex]; 200 // Array[CurrentIndex] = Temp; 201 // Num++; 202 // } 203 //} 204  } 205 return result; 206 }

枚举用于表示移动方向。

enum EnumDirection { up = 0, down = 1, left = 2, right = 3, }

15.冒泡排序

 1 class Program  2  {  3 static void Main(string[] args)  4 {//8 1 9 3 6 9  5 int n = 6;//数组长度  6  7 int[] Array = { 8, 1, 9, 3, 6, 8 };  8  9  BubbleSort(n, Array); 10 11 foreach (var item in Array) 12  { 13  Console.WriteLine(item); 14  } 15  } 16 17 private static void BubbleSort(int n, int[] Array) 18  { 19 int Temp = 0; 20 21 for (int j = 0; j < n - 1; j++) 22  { 23 for (int i = 0; i < n - 1 - j; i++) 24  { 25 if (Array[i] > Array[i + 1]) 26  { 27 Temp = Array[i]; 28 Array[i] = Array[i + 1]; 29 Array[i + 1] = Temp; 30  } 31  } 32  } 33  } 34 }

16.插入排序

 1 class Program  2  {  3 static void Main(string[] args)  4  {  5 int[] Array = new int[6] { 10, 5, 7, 9, 6, 15 };  6 //Array[6] = int[6];  7 int n = 6;  8  9  Insertion_Sort(Array); 10 11 foreach (var item in Array) 12  { 13  Console.WriteLine(item); 14  } 15 16  } 17 18 private static void Insertion_Sort(int[] Array) 19  { 20 int End = 0; 21 int Value = 0; 22 for (int i = 1; i < Array.Length; i++) 23  { 24 Value = Array[i]; 25 End = i - 1; 26 27 while (End > -1 && Array[End] < Value) 28  { 29 Array[End + 1] = Array[End]; 30 End--; 31  } 32 Array[End + 1] = Value; 33 34  } 35  } 36 }

17.根据学生数量以及科目录入学生成绩

 1 class Program  2  {  3 static void Main(string[] args)  4  {  5 int NumOfStu = GetNumOfStu();  6 int NumOfSub = GetNumOfSub();  7  8 int[,] ScoreTable = GetScoreTable(NumOfStu, NumOfSub);  9 10  ShowTable(ScoreTable); 11  } 12 13 private static int GetNumOfStu() 14  { 15 Console.WriteLine("请输入学生总数:"); 16 int NumOfStu = int.Parse(Console.ReadLine()); 17 18 return NumOfStu; 19  } 20 private static int GetNumOfSub() 21  { 22 Console.WriteLine("请输入科目数:"); 23 int NumOfSub = int.Parse(Console.ReadLine()); 24 25 return NumOfSub; 26  } 27 28 private static int[,] GetScoreTable(int NumOfStu,int NumOfSub) 29  { 30 int[,] ScoreTable = new int[NumOfStu, NumOfSub]; 31 32 for (int IndexOfStu = 0; IndexOfStu < NumOfStu; IndexOfStu++) 33  { 34 for (int IndexOfSub = 0; IndexOfSub < NumOfSub; IndexOfSub++) 35  { 36 Console.WriteLine($"请输入第{IndexOfStu + 1}名学生的科目{IndexOfSub+1}的成绩:"); 37 ScoreTable[IndexOfStu, IndexOfSub] = int.Parse(Console.ReadLine()); 38  } 39  } 40 41 return ScoreTable; 42  } 43 44 private static void ShowTable(int[,] ScoreTable) 45  { 46 47 for (int IndexOfStu = 0; IndexOfStu < ScoreTable.GetLength(0); IndexOfStu++) 48  { 49 50 for (int IndexOfSub = 0; IndexOfSub < ScoreTable.GetLength(1); IndexOfSub++) 51  { 52 Console.Write(ScoreTable[IndexOfStu, IndexOfSub]+"\t"); 53  } 54 Console.Write("\n"); 55  } 56  } 57 }

18.选择排序

 1 class Program  2 {//8 1 9 3  3 static void Main(string[] args)  4  {  5 int[] Array = new int[] { 8, 1, 9, 3 };  6  SelectSort(Array);  7 foreach (var item in Array)  8  {  9  Console.WriteLine(item); 10  } 11  } 12 13 private static void SelectSort(int[] Array) 14  { 15 int Temp = 0; 16 17 for (int j = 0; j < 3/*数组长度减一*/; j++) 18  { 19 for (int i = 1; i < 4/*数组长度*/- j; i++) 20  { 21 if (Array[j] > Array[j + i]) 22  { 23 Temp = Array[j]; 24 Array[j] = Array[i + j]; 25 Array[i + j] = Temp; 26  } 27  } 28  } 29  } 30 }

 19.String单词反转,去重。

 1 class Program  2  {  3 static void Main(string[] args)  4  {  5 Console.WriteLine(WordsReverse("How Are You"));  6 Console.WriteLine(WordsReverse02("How Are You"));  7 Console.WriteLine(RemoveDuplication("How Are You"));  8  }  9 10 11 //方法一,单词反转。 12 private static string WordsReverse(string str) 13  { 14 15 StringBuilder result = new StringBuilder(); 16 string[] Words = str.Split(' '); 17 18 for (int i = 0; i < Words.Length; i++) 19  { 20 result.Append(Words[Words.Length - i - 1]); 21 result.Append(' '); 22  } 23 return result.ToString(); 24  } 25 26 //方法二,单词反转 27 private static string WordsReverse02(string str) 28  { 29 string[] Words = str.Split(' '); 30  Array.Reverse(Words); 31 string result = String.Join(" ", Words); 32 return result; 33  } 34 35 //方法三,查找指定字符串中不重复的文字 36 37 private static string RemoveDuplication(string str) 38  { 39 StringBuilder result = new StringBuilder(str.Length); 40 for (int i = 0; i < str.Length; i++) 41  { 42 if (result.ToString().IndexOf(str[i]) < 0) result.Append(str[i]); 43  } 44 return result.ToString(); 45  } 46 }

 20.自定义数组集合(数组的封装)

用户类:

 1 class User  2  {  3 private string userId;  4 public const string defaultPassword = "123456";  5 public string UserId  6 { set; get; }  7 public string Password { set; get; }  8  9 10 public User() 11  { 12 13  } 14 15 public User(string userId, string password = defaultPassword) 16  { 17 this.UserId = userId; 18 this.Password = password; 19 20 }

自定义用户集合类:

 1 class UserList  2  {  3  4 private User[] UserArray;  5  6 private int capacity;  7 public int Capacity { private set { capacity = value; } get { return capacity; } }  8  9 private int count;  10 public int Count { private set; get; }  11 public UserList() : this(10)  12  {  13  14  }  15  16 public UserList(int capacity)  17  {  18 this.UserArray = new User[capacity];  19 this.Capacity = capacity;  20 this.Count = 0;  21  }  22  23 public void Add(string userId, string password)  24  {  25 User user = new User(userId, password);  26  CheckCapacity();  27 this[this.Count++] = user;  28  }  29 public void Add(string userId)  30  {  31 User user = new User(userId);  32  CheckCapacity();  33 this[this.Count++] = user;  34  }  35 public void Add(User user)  36  {  37  CheckCapacity();  38 this[this.Count++] = user;  39  }  40  41 private void CheckCapacity()  42  {  43 if (this.Count == Capacity)  44  {  45 Capacity *= 2;  46 User[] newUserArray = new User[Capacity];  47 UserArray.CopyTo(newUserArray, 0);  48 this.UserArray = newUserArray;  49  }  50  }  51  52 public User this[int index]  53  {  54 get  55  {  56 if (index < Capacity) return UserArray[index];  57 else throw Exception("索引数字不和逻辑或者大于总数量!");  58  }  59  60 set  61  {  62 if (index < Capacity) UserArray[index] = value;  63 else throw Exception("索引数字不和逻辑或者大于总数量!");  64  }  65  }  66  67 //public void PrintUser(User user)  68 //{  69 // Console.WriteLine($"账号:{user.UserId},密码:{user.Password}");  70 //}  71  72 public void Insert(User user, int index)  73  {  74 if (index > Capacity - 1) throw Exception("索引数字不和逻辑或者大于总数量!");  75  CheckCapacity();  76 if (index > Count - 1)  77  {  78 this[index] = user;  79 count++;  80  }  81  82 else  83  {  84 for (int i = Count++ - 1; i >= index; i--)  85  {  86 this[i + 1] = this[i];  87  }  88 this[index] = user;  89  }  90  }  91  92 public void Delete(int index)  93  {  94 if (index > Capacity - 1) throw Exception("索引数字不和逻辑或者大于总数量!");  95 if (this[index] == null) throw Exception("该索引指向的列表元素为空");  96 this[index] = null;  97 this.Count++;  98  }  99 100 private Exception Exception(string v) 101  { 102 throw new NotImplementedException(v); 103 }

测试代码:

 1 class Program  2  {  3 static void Main(string[] args)  4  {  5  6 UserList uList = new UserList(3);  7 uList.Add("u01");  8 uList.Add("u02", "098765");  9 User u03 = new User(); 10  uList.Add(u03); 11 for (int i = 0; i < uList.Capacity; i++) 12  { 13 if (uList == null) 14  { 15  Console.WriteLine(i); 16  } 17 else 18  { 19 Console.WriteLine(uList[i].UserId + "/" + uList[i].Password); 20  } 21 22  } 23 /*输出结果: 24  *u01/123456 25  *u02/098765 26  *null/null 27 */ 28 //成功实现userList的添加功能,并且通过索引器访问User数组 29 uList.Add("u04"); 30 uList.Add("u05"); 31  Console.WriteLine(uList.Capacity); 32 for (int i = 0; i < uList.Capacity; i++) 33  { 34 if (uList[i] == null) 35  { 36 Console.WriteLine(i + 1); 37  } 38 else 39  { 40 Console.WriteLine(uList[i].UserId + "/" + uList[i].Password); 41  } 42  } 43 44 /*输出结果: 45  *6 46  *u01 / 123456 47  *u02 / 098765 48  *null/null 49  *u04 / 123456 50  * u05 / 123456 51  * 5 52 */ 53 //成功实现userList的自动扩容 54 uList.Delete(1); 55 //uList.Delete(6);报错! 56 for (int i = 0; i < uList.Capacity; i++) 57  { 58 if (uList[i] == null) 59  { 60 Console.WriteLine(i + 1); 61  } 62 else 63  { 64 Console.WriteLine(uList[i].UserId + "/" + uList[i].Password); 65  } 66  } 67 //实现删除功能 68 69  } 70 }

 21.结构体的应用,实现获取一个二维数组中某个元素的各个方向上的其他元素。

1)定义结构体

 1 struct Direction  2  {  3 private int rindex;  4  5 public int Rindex  6  {  7 get  8  {  9 return rindex; 10  } 11  } 12 13 private int cindex; 14 public int Cindex 15  { 16 get 17  { 18 return cindex; 19  } 20  } 21 22 private Direction(int rindex,int cindex) 23  { 24 this.rindex = rindex; 25 this.cindex = cindex; 26  } 27 28 public static Direction Up 29  { 30 get { return new Direction(-1, 0); } 31  } 32 public static Direction Down 33  { 34 get { return new Direction(1, 0); } 35  } 36 public static Direction Left 37  { 38 get { return new Direction(0, -1); } 39  } 40 public static Direction Right 41  { 42 get { return new Direction(0, 1); } 43  } 44 }

2)通过一个工具类实现获取,使用集合进行存储

 1 class ArrayHelper  2  {  3 public static string[] GetElements(string[,] array, int rindex, int cindex, Direction dir, int count)  4  {  5 List<string> elements = new List<string>(count);  6  7 for (int i = 0; i < count; i++)  8  {  9 rindex += dir.Rindex; 10 cindex += dir.Cindex; 11 if (rindex < 0 || rindex > array.GetLength(0) - 1 || cindex < 0 || cindex > array.GetLength(1) - 1) break; 12  elements.Add(array[rindex, cindex]); 13  } 14 15 return elements.ToArray(); 16 17  } 18 }

3)测试:

class Program { static void Main(string[] args) { string[,] array = new string[4, 5]; for (int j = 0; j < 4; j++) { for (int i = 0; i < 5; i++) { array[j, i] = j.ToString() + i.ToString(); } } for (int j = 0; j < 4; j++) { for (int i = 0; i < 5; i++) { Console.Write(array[j,i]+"\t"); } Console.WriteLine(); } string[] result = ArrayHelper.GetElements(array, 1, 0,Direction.Right,4); foreach (var item in result) { Console.Write(item+"\t"); } } /*00 01 02 03 04 10 11 12 13 14 20 21 22 23 24 30 31 32 33 34 */

测试结果:

<span role="heading" aria-level="2">C#代码集

 

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

发布者:全栈程序员-用户IM,转载请注明出处:https://javaforall.cn/154595.html原文链接:https://javaforall.cn

【正版授权,激活自己账号】: Jetbrains全家桶Ide使用,1年售后保障,每天仅需1毛

【官方授权 正版激活】: 官方授权 正版激活 支持Jetbrains家族下所有IDE 使用个人JB账号...

(0)
blank

相关推荐

  • Shell脚本编程_shell简单脚本

    Shell脚本编程_shell简单脚本文章目录1.shell概述1.1shell和shell脚本1.2Shell脚本应用场景1.4shell类型1.shell概述1.1shell和shell脚本  shell是指一种应用程序,这个应用程序提供了一个界面,用户通过这个界面访问操作系统内核的服务,在用户和内核之间充当翻译官的角色,是一个命令解释器。KenThompson的sh是第一种UnixShell,WindowsExplorer是一个典型的图形界面shell。  shell脚本(

  • Promise的含义和用法「建议收藏」

    Promise的含义和用法「建议收藏」含义Promise是异步编程的一种解决方案。Promise对象有以下2个特点:1.对象的状态不受外界影响。Promise对象代表一个异步操作,有三种状态:Pending(进行中)、Resolved(已完成)和Rejected(已失败)。只有异步操作的结果,可以决定当前是哪一种状态,任何其他操作都无法改变这个状态。这也是Promise这个名字的由来,它的英语意思就是“承诺”,表示其…

  • ElasticSearch最新版快速入门详解「建议收藏」

    ElasticSearch最新版快速入门详解「建议收藏」本文把最新版的ElasticSearch和kibana的知识点用通俗易懂的语言来展现,并会在核心概念上和MySql对比,结合示例进行图文并茂的详解,同时还给大家提供百分百成功的极速安装配置方法哦!

  • C++多线程通信_c++ socket 多线程

    C++多线程通信_c++ socket 多线程参考:https://m.imooc.com/article/289630C++11标准库新引入的线程库https://www.jianshu.com/p/e5a3498ba930(一)多线程编程#include<iostream>#include<thread>#include<mutex>#include<condi…

  • 奇怪的电梯

    奇怪的电梯奇怪的电梯【问题描述】某栋大楼有一种很奇怪的电梯。大楼的每一层楼都可以停电梯,而且第i层楼(1≤i<N)上有一个数字K(≤K≤N)电梯只有四个按钮:开、关、上、下。上、下的层数等于当前楼层上的那个数字。当然,如果不能满足要求,相应的按钮就会失灵。例如:33125代表了Ki(K1=3,K2=3,…),从一层开始。在一层按“上”可以到4层,按“下”是不起作用的,因为没有-2层。那么从A层到B层至少要按几次按钮呢?【输入格式】第1行为3个用1个空格隔开的正整数,表示N、A、B(l≤N≤200,1≤

  • Oracle 11G CRUD操作监控单个表

    Oracle 11G CRUD操作监控单个表

发表回复

您的电子邮箱地址不会被公开。

关注全栈程序员社区公众号