基础笔记

  1. ///:第三类注释,用于说明代码
  2. <code line x,statement y>并不是真正的C#代码,而是用这个文本作为C#语句的占位符。
  3. sbyte=System.SByte   有符号的两个字节数字
  4. byte=System.Byte  无符号的两个字节数字
  5. short=System.Int16        int=System.Int32        long=System.Int64
  6. float=System.Single         double=System.Double   decimao=System.Decimal:1.0×10^-28~7.9×10^28
  7. Char=System.Char          bool=System.Boolean     string=System.String
  8. Console.WriteLine("{0} {1}",myString,myInteger);     字符串的每对花括号都是一个占位符,包含列表中每个变量的内容。
  9. 变量名第一个字符必须是字母、下划线或@。
  10. 一元+:var1=+var2;      var1的值等于var2的值
  11. 一元-: var1=-var2;       var1的值等于var2的值除乘以-1?
  12. 字符串+:var1=var2+var3;    连接
  13. double firstNumber=Convert.ToDouble(Console.ReadLine());   
  14. namespace LevelOne
    {
        using LevelTwo;
        //using LT=LevelTwo;
        namespace LevelTwo
        {
            //define NameTwo
            
        }
    }
    //LevelOne.LevelTwo.NameTwo==LevelTwo.NameTwo
  15. System命名空间是.Net Framework应用程序的根命名空间,包含控制台应用程序所需要的所有基本功能。
  16. 左移运算符<<:    var1=var2<<var3;   var2的二进制值向左移动var3位,低位补零。乘以2的var3次幂
  17. 右移运算符>>:    var1=var2>>var3;   var2的二进制值向右移动var3位,高位补零。除以2的var3次幂 
  18. >>=  一元   var1>>=var2;      把var1的二进制值向右移动var2位,得到为var1的值。
  19. <<=  一元   var1<<=var2;      把var1的二进制值向左移动var2位,得到为var1的值。
  20. 隐式转换规则:任何类型A,只要其取值范围完全包含在类型B的取值范围内,就可以隐式转换为类型B。
  21. 显示转换:(destinationType)sourceVar。
  22. checked、unchecked,称为表达式的溢出检查内容    destinationVar=(un)checked((byte)sourceVar),unckecked表示默认操作。
  23. 枚举类型:enum typeName:underlyingType {} 
    enum orientation
    {
        ...
    }

        

  24. 结构类型:struct <typeName>{...}

    struct route
    {
        public orientation direction;
        public double distance;
    }

     

  25. 数组类型:<baseType>[]<name>;

    数组必须在访问之前初始化
    数组初始化有两种方式:
    int [] myIntArray={5,9,10,2,99};
    int [] myIntArray=new int[arraySize];   //显示初始化数组,所有元素赋予同一个默认值0
    int [] myIntArray=new int[5]{5,9,10,2,99};    //数组大小必须与元素个数相匹配,如果是变量定义其大小,必须是常变量,可以通过myIntArray.Length确定数组中的元素个数

        

  26. foreach循环:定位数组中的每个元素
    foreach(<baseType><name>in<array>){//can use <name> for each element}

    static void Main(string[] args)
    {
        string[] friendNames={"Jim","Tom","Mary"};
        Console.WriteLine("Here are {0} of my friends:",friendNames.Length);
        foreach(string friendName in friendNames)
        {
            Console.WriteLine(friendName);
        }
    }
    //foreach循环对数组内容进行只读访问,所以不能改变任何元素的值

       

  27. 二维数组声明:<baseType>[,]<name>;      

    double[,] hillHeight=new double[3,4];
    double[,] hillHeight={{1,2,3,4},{2,3,4,5},{3,4,5,6}};
    hillHeight[2,1]==4;

     

  28. 多维数组声明:<baseType>[,,,]<name>;(四维)

  29. 变长数组:每行都有不同的元素个数。
    int[][] jaggedIntArray;
    jaggedIntArray=new int[2][];
    jaggedIntArray[0]=new int[3];
    jaggedIntArray[1]=new int[4];
    or
    jaggedIntArray={new int[]{1,2,3},new int[]{1},new int[]{1,2}};
    使用foreach循环:

    foreach(int[] jaggedOfIntArray in jaggedIntArray)
    {
        foreach(int jaggedOfnumber in jaggedOfIntArray)
        {
            Console.WriteLine(jaggedOfnumber);
        }
    }

       

  30. 删除字符串内容前面或后面添加的额外空格,可以使用<string>.Trim()命令处理

    string userResponse=Console.ReadLine();
    userResponse=userResponse.Trim();
    if(userResponse.ToLower()=="yes")
    {
        ...
    }
    
    
    char[] trimChars={' ','e','s'};
    string userResponse=Console.ReadLine();
    userResponse=userResponse.ToLower();
    userResponse=userResponse.Trim(trimChars);
    if(userResponse=='y')
    {
        ...
    }

    <string>TrimStart()和<string>.TrimEnd()可以把字符串的前面或后面的空格都删掉
    <string>.PadLeft(<desiredLength>)和<string>.PadRight()可以在字符串的左边或右边添加空格,是字符串达到指定的长度

    myString="Aligned";
    myString=myString.PadLeft(10);        //   Aligned
    myString=myString.PadLeft(10,'-');    //---Aligned
    
    
    
    string myString="This is a test.";
    char[] separator={' '};
    string[] myWords;
    myWords=myString.Split(separator);    //使用<string>.Split()命令将string转换为string数组,在指定的位置分隔开,删除了分隔符

        

  31. 方法:特定类型的函数

  32. 函数定义:
    Main是控制台应用程序的入口点函数
    关键字static与面向对象的概念相关
    参数数组:

    class Class1
    {
        static int sumVals(params int[] vals)   
        {
            int sum=0;
            foreach(int val in vals)
            {
                sum+=val;
            }
            return sum;
        }
    
        static void Main(string[] args)
        {
            int sum=sumVals(1,5,2,9,8);   //无限制个数
            Console.WriteLine("Summed Values={0}",sum);
        }
    }
    
    
    //参数数组特别适合于为在处理过程中要使用的函数指定其他信息。
    string firstWord=getWord("This is a sentence.");    //返回This
    string firstWord=getWord("This is a sentence.",2);    //返回is
    string firstWord=getWord("This is a sentence.",4,3);    //返回sen

    引用传递参数:函数处理的变量与函数调用中使用的变量相同

    //定义:
    Static void ShowDouble(ref int val)
    {
        ...
    }
    //调用:
    ShowDouble(ref myNumber);
    //ref参数的限制:myNumber必须是变量,而且必须是初始化过的变量
    

    输出参数:使用out关键字,指定给定的参数是一个输出参数

    //定义:
    Static int MaxValue(int[] intArray,out int maxIndex)
    {
        int maxVal=...
        ...
        return maxVal;
    }
    //调用:
    Console.WriteLine("The maximum value in myArray is {0}",MaxValue(myArray,out maxIndex));
    

    Main()函数:
    C#应用程序的入口点。四种签名:
    static void Main()
    static void Main(string[] args)       //参数args是从应用程序的外部接收信息的方法,这些信息在运行期间指定,其形式是命令行参数
    static int Main()                 //返回一个int值,用来一种错误提示,返回0表示正常终止
    static int Main(string[] args)

  33. 委托:
    是一种可以把引用存储为函数的类型。委托的声明非常类似于函数,但不带函数体,且要使用delegate关键字。委托的声明指定了一个函数签名,其中包含一个返回类型和参数列表。

    class Class
    {
        delegate double processDelegate(double param1,double param2);   //关键字delegate指定该定义用于委托,而不是用于函数,用一个签名指定double返回类型和两个double参数,可以任意调用委托类型和参数名
        static double Multiply(double param1,double param2)
        {
            return param1*param2;
        }
        static double Divide(double param1,double param2)
        {
            return param1/param2;
        }
        
        static void Main(string[] args)
        {
            processDelegate process;
            Console.WriteLine("Enter 2 number separated with a comma:");
            string input=Console.ReadLine();
            int commaPos=input.IndexOf(',');
            double param1=Convert.ToDouble(input.Substring(0,commaPos));
            double param2=Convert.ToDouble(input.Substring(commaPos+1,input.Length-commaPos-1));
            Console.WriteLine("Enter M to multiply or D to divide:");
            input=Console.ReadLine();
            if(input=="M")     //new关键字创建一个新委托,指定委托类型,并提供一个引用函数的参数,注意这个参数与委类型或目标函数的参数不匹配,参数是要使用的函数名,且不加括号
                process=new processDelegate(Multiply);
            else
                process=new processDelegate(Divide);
            Console.WriteLine("Result:{0}",process(param1,param2));   //把委托变量看作是一个函数名
        }
    }
    
    //委托变量的另外用法:
    Static void executeFunction(processDelegete process)     //通过参数把它传递给一个函数
    {
        process(2.2,3.3);
    }

       

  34. 调试:
     

    非中断模式调试:
    using System;
    using System.Diagnostics;    //使用命名空间
    
    namespace ConsoleApp2
    {
        class Program
        {
            static void Main(string[] args)
            {
                int[] testArray = { 4, 7, 4, 2, 7, 3, 7, 8, 3, 9, 1, 9 };
                int[] maxValIndices;
                int maxVal = Maxima(testArray, out maxValIndices);
                Console.WriteLine("Maximum value {0} found at element indices:", maxVal);
                foreach(int index in maxValIndices)
                {
                    Console.WriteLine(index);
                }
            }
    
            static int Maxima(int[] integers,out int[] indices)
            {
                Debug.WriteLine("Maximum value search started.");   //等价于System.Diagnostics.Debug.WriteLine();
                indices = new int[1];
                int maxVal = integers[0];
                indices[0] = 0;
                int count = 1;
                Debug.WriteLine("Maximum value initialized to " + maxVal + ",at element index 0.");
                for(int i = 1; i < integers.Length; i++)
                {
                    Debug.WriteLine("Now looking at element at index " + i + ".");
                    if (integers[i] > maxVal)
                    {
                        maxVal = integers[i];
                        count = 1;
                        indices = new int[1];
                        indices[0] = i;
                        Debug.WriteLine("New maximum found.New value is " + maxVal + ",at element index " + i + ".");
                    }
                    else
                    {
                        if (integers[i] == maxVal)
                        {
                            count++;
                            int[] oldIndices = indices;
                            indices = new int[count];
                            oldIndices.CopyTo(indices, 0);
                            indices[count - 1] = i;
                            Debug.WriteLine("Duplicate maximum found at element index " + i + ".");
                        }
                    }
                }
                Trace.WriteLine("Maximum value " + maxVal + " found,with" + count + " occurrences.");
                Debug.WriteLine("Maximum value search completed.");
                return maxVal;
            }
        }
    }
    

        

  35. 错误处理:
    C#语言包含结构化的异常处理,结构为try...catch...finally。
    事件处理顺序:try块在发生异常的地方中断程序执行,如果有catch块,检查是否匹配抛出的异常类型,如果类型匹配则执行包含代码,再执行finally块代码,如果不匹配则执行finally块代码。

    using System;
    using System.Diagnostics;    //使用命名空间
    
    namespace ConsoleApp2
    {
        class Program
        {
            static string[] eTypes = { "none", "simple", "index", "nested index" };
    
            static void Main(string[] args)
            {
                foreach(string eType in eTypes)
                {
                    try
                    {
                        Console.WriteLine("Main() try block reached.");
                        Console.WriteLine("ThrowException(\"{0}\")called.", eType);
    
                        ThrowException(eType);
                        Console.WriteLine("Main() try block continues.");
                    }
                    catch(System.IndexOutOfRangeException e)
                    {
                        Console.WriteLine("Main() System.IndexOutOfRangeException catch" + " block reached.Message:\n\"{0}\"", e.Message);
                    }
                    catch
                    {
                        Console.WriteLine("Main() general catch block reached.");
                    }
                    finally
                    {
                        Console.WriteLine("Main() finally block reached.");
                    }
                    Console.WriteLine();
                }
            }
    
            static void ThrowException(string exceptionType)
            {
                Console.WriteLine("ThrowException(\"{0}\")reached.", exceptionType);
                switch (exceptionType)
                {
                    case "none":
                        Console.WriteLine("Not throwing an exception.");
                        break;
                    case "simple":
                        Console.WriteLine("Throwing System.Exception.");
                        throw (new System.Exception());
                    case "index":
                        Console.WriteLine("Throwing System.IndexOutOfRangeException.");
                        eTypes[4] = "error";
                        break;
                    case "nested index":
                        try
                        {
                            Console.WriteLine("ThrowException(\"nested index\") try block reached.");
                            Console.WriteLine("ThrowException(\"index\") called.");
                            ThrowException("index");
                        }
                        catch (System.IndexOutOfRangeException e)
                        {
                            Console.WriteLine("Main() System.IndexOutOfRangeException catch" + " block reached.Message:\n\"{0}\"", e.Message);
                        }
                        catch
                        {
                            Console.WriteLine("ThrowException(\"nested index\") general catch block reached.");
                        }
                        
                        finally
                        {
                            Console.WriteLine("ThrowException(\"nested index\") finally block reached.");
                        }
                        break;
                }
            }
        }
    }
    

      

  36. OOP:面向对象编程。
    对象是OOP应用程序的一个构件,这个构件封装了部分应用程序。
    方法:用于表示对象中的函数
    接口:把隐式的公共方法和属性组合起来,以封装特定功能的一个集合

  37. C#类定义:
     

    范围:
    internal class MyClass    //声明类为内部的,只有当前工程中的代码才能访问
    {
        ...
    }
    
    public class MyClass    //指定类是公共的,可以由其他工程中的代码来访问
    {
        ...
    }
    
    public abstract class MyClass    //公共抽象类,abstract指定类是抽象的(不能实例化,只能继承,可以有抽象成员)
    {
        ...
    }
    
    public sealed class MyClass     //公共密封类,sealed指定类是密封的(不能继承,只能实例化)
    {
        ...
    }
    
    继承:
    public class MyBase
    {
        ...
    }
    internal class MyClass:MyBase
    {
        ...
    }
    C#只能有一个基类,如果继承一个抽象类,就必须执行所继承的所有抽象成员,否则派生类也是抽象类。
    编译器不允许派生类的可访问性比其基类更高,比如内部类可以继承一个公共类,但公共类不能继承一个内部类.
    所有类的根都是System.Object,如果没有使用基类,则被定义的类就只能继承基类System.Object
    
    public class MyClass:MyBase,IMyInterface
    {
        ...
    }
    
    public class MyClass:MyBase,IMyInterface,IMySecondInterface
    {    
        ...
    }
    所有的接口成员都必须在支持该接口的类中实现,但如果不想使用给定的接口成员,可以提供空的实现(没有代码)
    
    接口定义:(不包含执行代码,不能直接实例化,且必须是可以继承的)
    关键字是interface
    (public) interface IMyInterface   //关键字abstract和sealed不能在接口中使用
    {
        ...
    }
    
    public interface IMyInterface:IMyBaseInterface,IMyBaseInterface2   //可以使用多个基接口
    {
        ...
    }
    
    class MyClass
    {
        public readonly int MyInt=17;     //表示这个字段只能在执行构造函数的过程中赋值或由初始化赋值语句赋值
        public static int MyInt;    //字段可以使用static关键字声明为静态,静态字段只能通过定义它们的类来访问,而不能通过这个类的对象实例来访问
    }
    
    public class MyBaseClass
    {
        public virtual void DoSomething()   //virtual表示方法可以重写
        {
            ...
        }
    }
    public class MyDerivedClass:MyBaseClass
    {
        public override void DoSomething()   //override表示方法重写了一个基类方法
        {
            ...
        }
        public override sealed void DoSomething()   //sealed指定在派生类中不能对这个方法进一步修改,即这个方法不能由派生类重写
        {    
            ...
        }
    }

    接口:为了实现多重继承而产生,由于C#的类不支持多重继承。
    接口类不能实例化,但可以声明它们的变量。接口成员必须都在使用接口的类上执行(没有代码体),接口不能包含字段、构造函数、析构函数、静态成员或常量,接口主要是由类来使用。所有接口成员都是公共的,不能包含代码体,不能定义字段成员,不能用static,virtual,abstract或sealed关键字定义,如果要隐藏继承了基接口的成员,可以用new关键字定义

  38. 类对象是引用类型,在把对象赋给变量时,实际上是把带有一个指针的变量赋给了该指针所指向的对象
    结构类型对象是值类型,其变量并不是包含结构的指针。

  39. 字段、方法和属性都可以使用关键字static来声明,表示是属于类的静态成员,而不是对象实例的成员。

  40. 属性拥有两个类似于函数的块,一个块用于获取属性的值,另一块用于设置属性的值,分别用get和set关键字来定义

    private int myInt;     //类外部代码不能直接访问这个字段
    
    public int MyIntProp
    {
        get    //get字段必须有一个属性类型的返回值,一般与私有字段相关联以控制对这个字段的访问
        {
            return myInt;
        }
        set   //set把一个值赋给字段
        {
            if(value>=0&&value<=10)
                myInt=value;   //使用关键字value引用用户提供的属性值
            else
                throw(new ArgumentOutOfRangeException("MyIntProp",value,"MyIntProp must be assigned a value bettween 0 and 10."));
        }
    }
    
    

        

  41. 从基类继承一个成员就继承了其实现,无论继承的成员是否为虚拟,都可以隐藏其实现。如果有某个成员需要隐藏,可以使用new关键字显示说明
    使用base关键字,表示包含在派生类中的基类的实现base.DoSomething

  42. this关键字
    this用在类成员的内部,由this引用的对象实例是当前的对象实例(不能在静态成员中使用this关键字,因为静态成员不是对象实例的一部分)

    public void doSomething()
    {
        MyTargetClass myObj=new MyTargetClass();
        myObj.DoSomethingWith(this);
    }

       

  43. 嵌套类型定义:

    public class MyClass
    {
        public class myNestedClass
        {
            public int nestedClassField;
        }
    }
    
    在MyClass外部实例化myNestedClass,就必须限定名称:MyClass.myNestedClass myObj=new MyClass.myNestedClass()   如果嵌套的类声明为私有就不能这么做


       

  44. 控件:
    DialogResult dr = MessageBox.Show("测试消息对话框", "测试", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button1);   //创建一个可以快捷键反映的消息盒子
     

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值