C#基础学习(一)

---恢复内容开始---

1、最近被安排去做C#开发,然后开始一连串的看文档·看视屏,发现学C#给自己补了很多基础,C#每个函数变量什么都要先声名,而python可以直接定义;

一、数据类型

  1、整数类型:int  只能存整数

    小数类型 :double 能存整数和小数(15-16位)

    金钱类型:decimal 用来存储金钱,值后面加上一个m

    字符串类型:string  存数多个文本需要用双引号引起来

    字符类型:char 存储单个字符,单引号引起来

    布尔类型:bool

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace my_demo
{
    class Program
    {
        static void Main(string[] args)
        {
            //double >int 
            //显式类型转换 、自动类型转换
            // double = int (小转达)
            //隐士类型转换  
            // int = (int)dounle (大转小)
            Console.WriteLine("输入a:");
            int a = Convert.ToInt32(Console.ReadLine());
            Console.WriteLine("输入b:");
            int b = Convert.ToInt32(Console.ReadLine());
            a = a - b;
            b = a + b;
            a = b - a;
            Console.WriteLine("a = {0},b = {1}",a,b);
            Console.ReadKey(); 
        }
    }
}

 

    2 、条件、循环

  if条件:(vs2010代码对齐快捷键:Ctrl+k+d)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace 条件
{
    class Program
    {
        static void Main(string[] args)
        {
            //比较三个数字大小
            Console.WriteLine("输入第一个数字:");
            int number_1 = Convert.ToInt32(Console.ReadLine());
            Console.WriteLine("输入第一个数字:");
            int number_2 = Convert.ToInt32(Console.ReadLine());
            Console.WriteLine("输入第一个数字:");
            int number_3 = Convert.ToInt32(Console.ReadLine());
            if (number_1 > number_2)
            {
                if (number_1 > number_3)
                {
                    Console.WriteLine(number_1);
                }
                else
                {
                    Console.WriteLine(number_3);
                }
            }
            else
            {
                if (number_2 > number_3)
                {
                    Console.WriteLine(number_2);
                }
                else
                {
                    Console.WriteLine(number_3);
                }
            }
        }
    }
}
比较三个数字大小

 3、异常捕获

namespace 条件
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                Console.WriteLine("请输入一个年份:");
                try
                {
                    int year = Convert.ToInt32(Console.ReadLine());
                    Console.WriteLine("请输入一个月份:");
                    int month = Convert.ToInt32(Console.ReadLine());
                    if (month >= 1 && month <= 12)
                    {
                        int day = 0;
                        switch (month)
                        {
                            case 1:
                            case 3:
                            case 5:
                            case 7:
                            case 8:
                            case 10:
                            case 12: day = 31;
                                break;
                            case 2:
                                if ((year % 400 == 0) || (year % 4 == 0 && year % 100 != 0))
                                {
                                    day = 29;
                                }
                                else
                                {
                                    day = 28;
                                }
                                break;
                            default: day = 30;
                                break;
                        }
                        Console.WriteLine("{0}年{1}月{2}天", year, month, day);
                        
                    }
                    else
                    {
                        Console.WriteLine("月份输入错误");
                    }
                }//输入月份报错
                catch
                {
                    Console.WriteLine("月份输入错误");
                }
            }//出入年份报错
            catch
            {
                Console.WriteLine("年份输入错误");
            }
            Console.ReadKey();
        }
    }
}
switch使用判断月份天数

   4、do...while..循环

namespace 条件
{
    class Program
    {
        static void Main(string[] args)
        {
            string name = "";
            string pwd = "";
            do
            {
                Console.WriteLine("请输入用户名:");
                name = Console.ReadLine();
                Console.WriteLine("请输入密码:");
                pwd = Console.ReadLine();
            }
            while (name != "admin" && pwd != "123456");
            Console.WriteLine("登入成功");
            Console.ReadKey();
        }
    }
}
do while循环使用

  5、for 循环

namespace 循环
{
    class Program
    {
        static void Main(string[] args)
        {
            for (int i = 1; i <10; i++)

            {
                for (int j = 1; j<= i; j++)
                {
                    Console.Write("{0}*{1}={2} ", j, i, i * j);
                }
                Console.WriteLine();
            }
            Console.ReadKey();
        }
    }
}
九九乘法表

  6、类型转换

namespace 类型转换
{
    class Program
    {
        static void Main(string[] args)
        {
            int number = 0;
            //int numberOne = Convert.ToInt32("123");
            //int numner = int.Parse("123");
            bool b = int.TryParse("123a",out number);//无法转换但是不会报错
            Console.WriteLine(number);
            Console.ReadKey();
        }
    }
}
三种类型转换
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication6
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("请输入姓名");
            string name = Console.ReadLine();
            string result =  name == "老赵" ? "因材啊" : "流氓啊";
            Console.WriteLine(result);
            Console.ReadKey();
        }
    }
}
三元表达式

  7、常量(const)、枚举(enum)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{   //将枚举声名到命名空间下
    public enum Gender 
    { 
    男,女
    }
    class Program
    {
        const int  mun = 10;//常量不能被改变
        static void Main(string[] args)
        {
            Gender gender = Gender.男;
            Console.WriteLine(gender.ToString());//枚举类型转字符串
            string s = "11";
            Gender state = (Gender)Enum.Parse(typeof(Gender), s);//字符串转枚举
            Console.WriteLine(state);
            Console.ReadKey();
        }
    }
}
枚举

  8、结构(struct)

namespace ConsoleApplication1
{   
    public struct Person
    {
        public string _name;//字段
        public int _age;
        public Gender _gender;
    }
    public enum Gender
    {
        男, 女
    }
    class Program
    {
        const int mun = 10;//常量不能被改变
        static void Main(string[] args)
        {
            Person zs;
            zs._name = "张三";
            zs._age = 15;
            zs._gender = Gender.男;

            Person ls;
            ls._name = "李四";
            ls._age = 15;
            ls._gender = Gender.男;
            Console.ReadKey();
        }
    }
}
结构类型

  9、数组

namespace ConsoleApplication1
{

    class Program
    {
        const int mun = 10;//常量不能被改变
        static void Main(string[] args)
        {
            int[] nums = { 9, 8, 7, 6, 5, 4, 3, 2, 1, 0};
            //冒泡排序
            //for (int i = 0; i < nums.Length-1; i++)
            //{
            //    for (int j = 0; j < nums.Length-1-i; j++)
            //    {
            //        if (nums[j] > nums[j + 1]) {
            //            int temp = nums[j];
            //            nums[j] = nums[j + 1];
            //            nums[j + 1] = temp;
            //        }                    
            //    }
            //}
            Array.Sort(nums);
            Array.Reverse(nums);//逆向
            foreach (int i  in nums)
            {
                Console.WriteLine(i);
            }
            Console.ReadKey();
        }
    }
}
冒泡排序

二、方法

  函数是将一堆代码进行重用的一种机制

   1、 函数语法:

     [public] static 返回值类型 方法名( [参数列表]){ 方法体  }   

        public: 访问修饰符,公共的,哪都卡可以访问。            static:静态的 

     返回值类型:如果不返回值,写void

             方法名: Pascal 每个单词的首字母都大写。其余字母小写。

             参数列表: 完成这个方法所必须要提供给这个方法的条件。

namespace my_Dome02
{
    class Program
    {
        public static int _number = 10;//静态字段模拟全局变量
        static void Main(string[] args)
        {
            int b = 10;
            int a = 3;
            int ab = Test(a, b);//调用Test;a,b为实参
            Console.WriteLine(ab);
            Test02();
            Console.ReadKey();
        }
        public static int Test(int a,int b)//a,b形参
        {
            a += 5+b;
            return a;
        }
        public static void Test02()
        {
            Console.WriteLine(_number);//调用静态字段
        }
    }
}
方法使用

    2、out 、ref、 params使用

   1) 、out参数侧重于在一个方法中可以反悔多个不同类型的值       

namespace my_Dome02
{
    class Program
    {
        static void Main(string[] args)
        {
            int[] numbers = {1,2,3,4,5,6,7,8,9 };
            int max ;
            int min ;
            int sum;
            int avg;
            GetMaxMinSumAvg(numbers,out max,out min,out sum, out avg);
            Console.WriteLine("{0},{1},{2},{3}", max, min, sum, avg);
            Console.ReadKey(); 
        }
        public static void GetMaxMinSumAvg(int[] nums,out int max,out int min,out int sum, out int avg) {
            int[] res = new int[4];
            //假设res[0]最大值 res[1]最小值 res[2]总值 res[3]平均值
            max = nums[0];
            min = nums[0];
            sum = 0;
            for (int i = 0; i < nums.Length; i++)
            {
                if (nums[i] > max) {
                    max = nums[i];
                }
                if (min>nums[i])
                {
                    min = nums[i];
                }
                sum += nums[i];
            }
            avg = sum / nums.Length;
        }
    }
}
out使用

   2)、 ref能将一个变量带入一个方法中进行改变,在将改编后的值带出方法

namespace my_Dome02
{
    class Program
    {
        static void Main(string[] args)
        {
            //使用方法交换两个int类型变量
            int n1 = 10;
            int n2 = 20;
            Test(ref n1, ref n2);
            Console.WriteLine("{0} {1}", n1, n2);
            Console.ReadKey();
        }

        public static void Test(ref int n1,ref int n2) {
            int temp = n1;
            n1 = n2;
            n2 = temp;
        }
    }
}
ref使用

       ***ref要求必须在方法外赋值,out在方法内赋值

        3)、params将实参列表中跟可变参数数组类型一致的元素都当作数组元素去处理。

namespace my_Dome02
{
    class Program
    {
        static void Main(string[] args)
        {
            //求任意数组的和
            int sum = Getsum(99, 88, 77);//将后面的数值都变成数组传入
            Console.WriteLine(sum);
            Console.ReadKey(); 
        }
        public static int Getsum(params int[] nums)
        {
            int sum = 0;
            foreach (int i in nums)
            {
                sum += i;
            }
            return sum;
        }
    }
}
params求任意数组的和

  3、方法重载

  概念 : 方法名称相同参数不同

  4、方法的递归

    方法自己调用自己

namespace my_Dome02
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("请输入一个数字");
            string strNumberOne = Console.ReadLine();
            int numberOne = GetNumber(strNumberOne);
            Console.WriteLine("请输入一个数字");
            string strNumberTwo = Console.ReadLine();
            int numberTwo = GetNumber(strNumberTwo);
            Jude(ref numberOne,ref numberTwo);
            int sums = Getsums(numberOne, numberTwo);
            Console.WriteLine(sums);
            Console.ReadKey();
        }
        public static void Jude(ref int n1,ref int n2)//判断是否n1<n2
        {
            while (true)
            {
                if (n1 < n2)
                {
                    return;
                }
                else
                {
                    Console.WriteLine("第一个数字不能大于第二个数字,请重新输入第一个数字");
                    string s1 = Console.ReadLine();
                    n1 = GetNumber(s1);
                    Console.WriteLine("请重新输入第二个数字");
                    string s2 = Console.ReadLine();
                    n2 = GetNumber(s2);
                }   
            }

        }
        public static int GetNumber(string s)//判断用户输入是否为数字
        {
            while (true)
            {
                try
                {
                    int number = Convert.ToInt32(s);
                    return number;
                }
                catch
                {
                    Console.WriteLine("输入有误!!!请重新输入");
                    s = Console.ReadLine();

                }
            }
        }
        public static int Getsums(int n1, int n2) 
        {
            int sum = 0;
            for (int i = n1; i < n2; i++)
            {
                sum += i;
            }
            return sum;
        }
    }
}
用户输入两个值,必须第一个小于第二个,并且求他们之间所有数只和

   5、字符串的方法

    str.ToUpper()转大写   、str.ToLower()字符串转小写  、

    str1.Equaks(str2,,StringComparison.OrdinalIgnoreCase)比较两个字符串是否相同(加参数忽略大小写)

    string.Compare(str1,str2,ture) 比较(同上)

    str.Indexof() 索引位置、str.LastIndeOf() 从后开始所以

    str.EndsWith() 判断末尾是否存在字符串      str.StartsWith()判断开始是否存在字符串

    str.Split()分割字符串为数组     string.Join("-", array) 连接数组中的字符串  str.Replace(" ",",")替换    

    str.Contains(value)判断字符串中是否含有value

    str.Substring(int) 从索引int位置之前截取到末尾(默认)

    string,IsNullOrEmpty(str)判断str是否为空或者null

    str.Trim()一出前面和后面所有的空格  TrimStart()  TrimEnd()  和python中strip一样

namespace 面向对象002
{
    class Program
    {
        static void Main(string[] args)
        {
            StringBuilder sb = new StringBuilder();
            //创建一个计时器,用来记录程序运行时间
            Stopwatch sw = new Stopwatch();
            sw.Start();
            for (int i = 0; i < 1000000; i++)
            {
                //str+=i;//执行速度非常满
                sb.Append(i);
            }
            sw.Stop();
            string str1 = "wd_ld;o", str2 = "WD_LD;O";
            char[] chs = { ' ', '_' ,';'};
            string[] s = str1.Split(chs,StringSplitOptions.RemoveEmptyEntries);
            foreach (string i in s) { Console.WriteLine(i); }//s={"wd","id","o"}
            Console.WriteLine(string.Join("_", s));//join用“_”连接{"wd","id","o"}
            if (str1.Contains("wd")) { str1 = str1.Replace("wd", "ds"); }//str1 = "ds_ld;o"字符串替换
            string str3 = str1.Substring(0,2);//截取重0开始2个字符串
            int ui = str1.IndexOf("d",2);//索引第一次出线的位置,从的二个位置开始找
            int ui1 = str1.LastIndexOf("d");//从后开始索引
            Console.WriteLine(ui1);
            Console.WriteLine(str1.Equals(str2,StringComparison.OrdinalIgnoreCase));//比较
            Console.WriteLine(str1.Equals(str2, StringComparison.OrdinalIgnoreCase));
            Console.WriteLine(sw.Elapsed);
            Console.ReadKey();
        }
    }
}
实例

 

       

 

 

---恢复内容结束---

posted @ 2018-09-19 15:57  Huho  阅读(443)  评论(0编辑  收藏  举报