zoukankan      html  css  js  c++  java
  • C#深入总结

    面向对象编程好处:提高软件可复用性、可扩展性、易维护性、灵活性
    第一章:理解.NET Framework与C#

    1..NET框架由.NET Frmaework和CLR组成;

    2.CLR(公共语言运行时)由CTS(通用类型系统)和CLS(公共语言规范)组成
    CTS作用:解决不同语言的数据类型不同的问题
    CLS作用:是一种最低的语言标准,限制了由这些不同点引发的互操作性问题

    3.简单类库的使用:
    (1)ping与本机相连的IP
    using System.Net;
    using System.Net.NetworkInformation;
    private void btnPing_Click(object sender,EventArgs e)
    {
    Ping pingSender=new Ping();
    PingReply reply=pingSender.Send(txtIP.Text,200);
    if(reply.Status==IPStatus.Success)
    {
    string message=string.Formate("地址:{0}连接测试成功!",txtIP.Text);
    MessageBox.Show(message);
    }
    else
    {
    string message=string.Formate("地址:{0}连接测试失败!",txtIP.Text);
    MessageBox.Show(message);
    }
    }

    (2)下载图片到指定路径:
    using System.Net;
    using System.IO;
    private void btnDownload_Click()
    {
    try
    {
    if(!File.Exists("Bliss.jpg"))
    {
    WebClient webClient = new WebClient();
    webClient.DownloadFile(@"E:Bliss.jpg", "123.jpg");//123.jpg为Bliss.jpg改名后的图片的名字
    picShow.Image = Image.FromFile("123.jpg");
    }
    else
    {
    MessageBox.Show("你要下载的图片已经存在!");
    }

    }
    catch (Exception mes)
    {
    MessageBox.Show(mes.Message);
    }
    }

    4.使用正则表达式:
    using System.Text.RegularExpressions;
    private static bool ipIsPass(string ip)
    {
    Regex rx = new Regex(@"^((2[0-4]d|25[0-5]|[1]?dd?).){3}([2][5]?[0-4]?|[2][0-4]?[0-9]?|[2-9][0-9]?|[1][0-9]?[0-9]?)$");
    if (rx.IsMatch(ip))
    {
    return true;
    }
    else
    {
    return false;
    }
    }

    第二章:属性和方法
    1. C#中的几种类:
    普通类:public class Student
    抽象类:public abstract class Student
    部分类:public partial class Student
    静态类:public static class Student

    2.Java和.NET访问修饰符比较:
    Java:private、protected、default、public
    类或属性在缺省访问修饰符的情况下,默认都是default
    .NET:private、protected、internat、public
    (1)类或属性在缺省访问修饰符的情况下,默认都是internal,并且在包下面的类只能是internal或public,而类中的类可以用 任意的访问修饰符
    (2)方法或字段在缺省访问修饰符的情况下是private

    3.ref和out的区别:
    ref在调用前一定要赋值,调用的方法不一定要赋值
    out相反

    4.方法的重载:
    与方法是否为static无关,与返回类型无关,只与参数类型和参数个数有关

    5.构造函数的使用:
    public Student():this("李四","s25302")//调用自身类中的构造函数
    {

    }
    public Student(string name,string stuNo)
    {
    this.name=name;
    this.stuNo=stuNo;
    }
    注意:静态构造函数不能重载,不能带访问修饰符和参数

    6.命名规范:
    (1)Pascal命名法命名的法一般情况下适用于公有成员
    (2)Camel命名法命名的法一般情况下适用于私有成员
    (3)私有字段要在前面加上下划线如:private string _name;
    (4)Pascal:类名、方法名、属性、枚举、结构
    (5)Camel:字段、内联变量(传的参数)

    7.this相当于类的实例对象,this只能在类内部的实例方法中适用,它可以访问私有的变量

    第三章:值类型和引用类型
    1.获得当前系统时间:DateTime.Now

    2.求两个时间的差:
    DateTime TimeStart= DateTime.Now;
    DateTime TimeEnd = DateTime.Now;
    TimeSpan TimeStartToEnd = TimeEnd.Subtract(TimeStart);

    3.定义常量:访问修饰符 const数据类型 常量名=值
    const int Max_AGE=100;

    4.枚举:
    使用枚举好处:能够控制用户的输入,相当于sql中的约束
    应用:选择情况下使用,一般个数不超过10个
    注意:枚举是值类型,定义在命名空间下
    public enum Genders
    {
    Male=0,
    Female=1
    }
    获得枚举的整数值:
    stu.Gender=(Gender)(Enum.Parse(typeof(Genders),"Female"));
    Console.WriteLine(stu.Gender.ToString());//打印出1

    5.结构:是唯一可以new出来的值类型,在实际开发中不用结构而用类
    特征:值类型,不能带无参的构造函数,不能被继承,字段不能赋初值,构造函数必须对所有字段赋初值,不带参数的构造函数永 远不会被覆盖

    6.值类型:不能被实例化,不能等于null,值类型int、float、double、decimal、enum、struct、bool、char
    引用类型:传递的是地址,不是复制的数据或对象

    7.装箱和拆箱
    装箱:将值类型变成引用类型
    static void Main(string[] args)
    {
    int i=123;
    object o=i;//装箱
    i=456;
    Console.WriteLine("值类型的值为:",i);
    Console.WriteLine("引用类型的值为:",o);
    }
    拆箱:将引用类型变成值类型
    static void Main(string[] args)
    {
    int i=123;
    object o=i;
    try
    {
    int j=(int)o;
    System.Console.WriteLine("取消装箱成功!");
    }
    catch(System.InvalidCastException ex)
    {
    System.Console.WriteLine("{0}错误:不正确的取消装箱",ex.Message);
    }
    }

    8.索引器:封装了集合或数据的操作
    特征:1.没有静态索引器 2.索引器没有名字,用关键字是this
    注意:定义一个索引器的时候,要使用this关键字
    private Student[] students;

    public Student[] Students
    {
    get{return students;}
    set{students=value;}
    }
    public Student this[int index]
    {
    get {return students[index]}
    }
    public Student this[string name]
    {
    get
    {
    int i;
    bool found=false;
    for(i=0;i<students.Length;i++)
    {
    if(students[i].Name==name)
    {
    found=true;
    break;
    }
    }
    if(found)
    return students[i]
    else
    return null;

    }
    }

    第四章:用集合组织相关数据
    1.删除ArrayList中的元素:从尾巴开始,效率更高

    2.泛型集合:在System.Collection.Generic;中
    List<T>:T为该集合要存储的类型
    List<Student> students=new List<Student>();
    好处:List<T>比ArrayList有更大的类型安全性,因为取出元素的时候不需要类型转换

    Dictionary<k,v>:具有泛型的全部特性,编译时检查类型约束
    Dictionary<string,Student> students=new Dictionary<string,Student>();
    好处:Dictionary<k,v>比Hashtable 有更大的类型安全性,因为取出元素的时候不需要类型转换
    缺点:性能不高,很多情况下都不需要key值


    集合类型 | List<T> | Dictionary<K,V>
    ---------- -------------------------------- ---------------------------
    方法 RemoverAt(int index),Add(T value) Add(K key,V vlaue),Clear()
    Remove(T value),Clear() Remove(key),ContainsKey(key)
    ---------- -------------------------------- ---------------------------
    属性 Count Count,Keys,Values
    ---------- -------------------------------- ---------------------------
    访问元素 通过索引访问 通过键访问

    3.ICollection<Student> 是List<Student>和Dictionary<string,Student>的父类

    static List<Student> _stus = new List<Student>();

    static Dictionary<string, Student> _stus =new Dictionary<string, Student>();
    //两种都可以用GetAllStudent();
    internal static ICollection<Student> GetAllStudent()
    {
    return _stus.Values;
    }

    foreach (Student stu in StuMage.GetAllStudent())
    this.lstStu.Items.Add(stu);

    4.Thread.Sleep(2000);//可让程序暂停2秒钟

    第五章:文件读写与XML
    1.文件流:FileStream ---->基础流
    辅助流:必须借助基础流才能操作
    读写流:StreamReader
    写入流:StreamWriter

    2.所在命名空间:using System.IO;

    3.写入流:
    string path=txtFilePath.txt;
    string content=txtContent.txt;
    FileStream fs=new FileStream(path,FileMode.Create);
    StreamWriter sw=new StreamWriter(fs);
    sw.Writer(content);
    sw.Close();
    fs.Close();

    4.读写流:
    string path=txtFilePath.txt;
    string content="";
    FileStream fs=new FileStream(path,FileMode.Open);
    StreamReader sw=new StreamReader(fs);
    content=sw.ReadToEnd();
    txtContent.txt=content;
    sw.Close();
    fs.Close();

    5.文件流中FileMode的成员:
    Create 用指定的名称新建一个文件,会覆盖原来的文件
    CreateNew 新建一个文件,如果已经存在该文件则抛异常
    Open 打开一个文件,如果文件不存在会抛异常
    OpenOrCreate 如果不存在要打开的文件,则用指定的名称新建一个文件
    Append 在原来的文件内容后面追加新的内容

    6.StreamReader的方法成员:
    ReadLine() 读取一行数据
    ReadToEnd() 读取所有的内容
    Close() 关闭阅读器

    7.建议用法:
    string content="";
    using (FileStream fs=new FileStream(path,FileMode.Open))
    {
    using (StreamReader sr=new StreamReader(fs,Encoding.UTF8))
    {
    content=sr.ReadToEnd();
    txtContent.txt=content;
    }
    }

    8.文件和目录操作:
    File:对文件进行操作
    方法: Exists(string path)
    Copy(string SourceFilePath,string DestinationFilePath)
    Move(string sourceFileName,string destFileName)
    Delete(string path)

    Directory:对文件夹进行操作
    Exists(string path)
    Move(string soureDirName,string destDirName)
    Delete(string path,bool b) 如果b为true,则删除目录中的所有内容

    9.XML:
    对象 属性和方法 说明
    ----------------------------------------------------------------------------
    XmlDocument DocumentElement 获取根节点
    ChildNodes 获取所有子节点
    Load()方法 读取整个XML的结构
    ----------------------------------------------------------------------------
    XmlNode InnerText 当前节点的值
    Name 当前节点的名字
    ChildNodes 当前节点的所有子节点
    ----------------------------------------------------------------------------

    例子:
    <Student>
    <Name stuNo="s25301">张静静</Name>
    <Age>20</Age>
    <Hobby>唱歌</Hobby>
    <Name stuNo="s25302">周杰杰</Name>
    <Age>22</Age>
    <Hobby>耍双节棍</Hobby>
    </Student>

    获取XML中的内容:
    XMLDocument myXml=new XMLDocument();
    myXml.Load("Student.xml"); //读取指定的XML文档
    XMLNode student=myXml.DocumentElement; //读取XML的根节点,Name、Age
    foreach(XmlNode node in student.ChildNodes)
    {
    switch(node.Name)
    {
    case "Name":
    Console.WriteLine("姓名:{0},学号:{1}",node.InnerText,node.Attributes["stuNo"].InnerText);
    break;
    case "Age":
    Console.WriteLine("年龄:{0}",node.InnerText);
    break;
    case "Hobby":
    Console.WriteLine("爱好:{0}",node.InnerText);
    break;
    }
    }

    注意:myXml.DocumentElement.FirstChild 获取根节点的第一个子节点

    10.树形控件:
    例子:
    this.tvwStu.Nodes.Clear();

    XmlDocument doc = new XmlDocument();
    doc.Load("Exam.xml");

    //得到根节点
    XmlNode rootNode = doc.DocumentElement;

    //获取班级信息
    foreach (XmlNode classNode in rootNode.ChildNodes)
    {
    //获取班级名称
    string className = classNode.Attributes["className"].InnerText;

    TreeNode treeClassNode = new TreeNode(className);

    //获取班级学员信息
    foreach (XmlNode stuNode in classNode.ChildNodes)
    {
    //获取姓名
    TreeNode stuTreeNode = new TreeNode(stuNode.ChildNodes[0].InnerText);

    treeClassNode.Nodes.Add(stuTreeNode);
    }

    //将节点添加到树形控件
    this.tvwStu.Nodes.Add(treeClassNode);
    }

    第六章:继承
    1.作用:实现软件中的代码复用、提高程序的简洁与高效

    2.注意:构造函数不可被继承、父类的实例不能访问子类的方法

    3.is-a关系:子类 is a 父类

    4.base关键字:base相当于父类的实例对象、但base可以访问父类中protected修饰的属性和方法,而实例对象则不能
    this关键字:不能访问父类的的私有成员

    5.密封类:用sealed关键字修饰的类。该类不能被继承

    6.如果父类有一个有参数的构造函数并且子类没有用base关键字指明调用哪一个构造函数,则父类一定要写一个无参数的构造函数
    因为子类会默认调用父类的无参构造函数

    7.显示调用父类的构造函数
    public Student():base("张静静",20,Genders.Female){}

    8.is关键字:if(父类 is 子类){} 接口是if(子类 is 父类){}

    9.继承的传递性:如果class A:B;class B:C,则A也可以访问C的成员

    第七章:多态
    1.子类重写父类的方法,父类作为参数,在运行的时候根据创建的不同的实例,去调用相应的方法

    2.派生类的访问修饰符不能高于父类

    3.抽象类:
    (1)作用:规范派生类的方法
    (2)例子:abstract public class Person{public abstract void SayHi();}
    (3)子类如果继承类抽象类,则子类应实现抽象类中定义的所有的抽象方法 public override void SayHi(){}
    (4)抽象类中可以定义非抽象方法和属性,但不能写静态的或者是sealed修饰的
    (5)抽象类中可定义虚方法

    4.
    override和new的区别:
    new是覆盖,子类中的方法名和父类的方法名相同,但子类没有用override,则方法名前默认调用new关键字
    override是重写父类中的方法,在继承的时候用到

    5.is和as关键字只能针对引用类型,不能针对值类型
    is用法:if(父类 is 子类){}
    as用法:Students stu=Student[i] as Student;//相当于强转当前的对象为指定的对象,转化失败时,不会引发异常,会返回一 个null值

    6.override必须和virtual、abstract、override(三重继承的时候)一起用

    第八章:接口
    1.作用:接口是一套规范和标准,实现了该接口的类必须实现接口中定义的所有方法及属性

    2.IComparable接口:类型不安全,不能实现多排序(例如:即可实现按姓名排序又可实现按年龄排序),只能按姓名排序或者按年龄排 序
    例子:class Student:Person,IComparable
    {
    public int CompareTo(object obj)
    if(!(obj is Student))
    {
    throw new Exception("只能是Student对象的比较");
    }
    Student other=obj as Student;
    return this.Name.CompareTo(other.Name);
    }

    3.类的默认排序:(1)实现:IComparable<T>的CompareTo(T t)方法 (2)缺点:不能实现多元排序和符合排序
    一个对象的多元排序:(1)实现:IComparer(T)的Compare(T t)方法 (2)缺点:定义了很多个很简单的类,不能实现复合排序
    备注:复合排序实现:(1)通过数据库 (2)在2008c#中Linq(Linq to object)

    例子:
    public class NameComparer:IComparer<Student>
    {
    public int Compare(Student x,Student y)
    return (x.Name.CompareTo(y.Name));
    }

    public class AgeComparer:IComparer<Student>
    {
    public int Compare(Student x,Student y)
    return (y.Age.CompareTo(y.Age));
    }

    调用:
    private void TestDefaultSort()
    {
    InitStudents();
    students.Sort(new NameComparer());
    PrintStudents(students);
    }

    private void TestAgeSort()
    {
    InitStudents();
    students.Sort(new AgeComparer());
    PrintStudents(students);

    }

    4.接口作为参数就是要传递一个实现了这个接口的对象。接口作为返回值就是要返回一个实现了这个接口的对象

    5.接口和抽象类的比较:
    -------------------------------------------------------------------------------------
    抽象类 接口
    -------------------------------------------------------------------------------------
    用abstract定义 用interface定义
    类只能继承一个抽象类 类可一个实现多个接口
    不同点:非抽象派生类必须实现抽象方法 实现接口的类必须实现所有的成员
    需要override实现抽象方法 直接实现
    -------------------------------------------------------------------------------------
    不能实例化
    相同点:包含未实现的方法
    派生类必须实现未实现的方法
    -------------------------------------------------------------------------------------

    第九章:序列化和反序列化
    1.作用:(1)不容易出错,操作简单 (2)通过序列化一个对象从一个应用程序发送到另一个应用程序中 (3)在远程通信中使用广泛

    2.二进制序列化--------->同一套应用程序中使用
    命名空间:using System.RunTime.Serialization..Formatters.Binary;
    条 件:(1)要有[Serializable]修饰类 (2)与被序列化相关的类也应有[Serializable]修饰
    实 例:pulbic void Save()
    {
    using (FileStream fs=new FileStream("profile.bin",FileMode.Create))
    {
    BinaryFormatter bf=new BinaryFormatter();
    bf.Serialize(fs,Profile);
    }
    }

    public void Load()
    {
    using (FileStream fs=new FileStream("profile.bin",FileMode.Create))
    {
    BinaryFormatter bf=new BinaryFormatter();
    Profile=(Profile)bf.Deserialize(fs);
    }
    }

    3.Xml序列化 --------->跨应用程序使用(应用更广)
    命名空间:using System.Xml.Serialiable;
    条 件:(1)不需要[Serializable]修饰 (2)类必须是public的 (3)相关的类必须要有默认的构造函数 (4)Xml只能序列化 共有成员
    实 例:
    //1: xml基本操作和序列化
    //2: DTD
    //3: Schame
    //4: xlst
    //5: dso
    class Program
    {
    static void Main(string[] args)
    {
    ExamInfo exam = new ExamInfo(2);

    using (FileStream fs = new FileStream("exam2.xml", FileMode.Create))
    {
    XmlSerializer seri = new XmlSerializer(typeof(ExamInfo));
    seri.Serialize(fs, exam);
    }
    }

    /// <summary>
    /// 创建xml
    /// </summary>
    static void CreateXml()
    {
    XmlDocument doc = new XmlDocument();
    //xml指令信息
    StringBuilder str=new StringBuilder("<?xml version="1.0" encoding="utf-8" ?>");
    //创建根节点,只能有一个
    str.Append(
    string.Format("<examInfo examDate="{0}"></examInfo>",
    System.DateTime.Now.ToString("d")));

    doc.LoadXml(str.ToString());

    doc.Save("Exam.xml");
    }

    static void CreateClassDate()
    {
    XmlDocument doc = new XmlDocument();
    //加载xml文件
    doc.Load("Exam.xml");

    //获取根节点
    XmlNode root = doc.DocumentElement;

    //创建classInfo节点
    XmlNode classNode = doc.CreateElement("classInfo");

    //创建className属性
    XmlAttribute className = doc.CreateAttribute("className");
    //属性赋值
    className.Value = "P0703Y2";
    //属性添加到classNode
    classNode.Attributes.Append(className);

    className = doc.CreateAttribute("description");
    //属性赋值
    className.Value = "晚班";
    //属性添加到classNode
    classNode.Attributes.Append(className);

    //把classInfo加到根节点
    root.AppendChild(classNode);

    CreateStudent(classNode, doc);

    doc.Save("Exam.xml");
    }

    static void CreateStudent(XmlNode classNode, XmlDocument doc)
    {
    for (int i = 1; i <= 9; i++)
    {
    XmlNode Student = doc.CreateElement("student");

    XmlAttribute attr = doc.CreateAttribute("stuID");
    attr.InnerText = "P07030" + i;
    Student.Attributes.Append(attr);

    attr = doc.CreateAttribute("status");
    attr.InnerText = "应届";
    Student.Attributes.Append(attr);

    attr = doc.CreateAttribute("examID");
    attr.InnerText = "P0703080" + i;
    Student.Attributes.Append(attr);

    XmlNode node = doc.CreateElement("name");
    node.InnerText = "张三" + i;
    Student.AppendChild(node);

    node = doc.CreateElement("age");
    node.InnerText = (23 + i).ToString();
    Student.AppendChild(node);

    node = doc.CreateElement("sex");
    node.InnerText = i % 2 == 0 ? "true" : "false";
    Student.AppendChild(node);

    node = doc.CreateElement("idCard");
    node.InnerText = "12345678998765432" + i;
    Student.AppendChild(node);

    XmlNode result = doc.CreateElement("examResult");

    node = doc.CreateElement("writtenExam");
    node.InnerText = (65 - i).ToString();
    result.AppendChild(node);

    node = doc.CreateElement("labExam");
    node.InnerText = (65 + i).ToString();
    result.AppendChild(node);

    Student.AppendChild(result);

    classNode.AppendChild(Student);
    }
    }
    }

    4.二进制和XML比较:
    A:应用程序无关 ------>XML好
    B:安全性 ------>二进制好
    C:占用空间 ------>二进制好
    D:Web兼容 ------>XML好

    5.反射:查找程序集的信息
    //获取版本号
    static void Main(string[] args)
    {
    string version=Assembly.LoadFile(@"D:MyNewReader.exe").GetName().Version.ToString();
    Console.WriteLine(version);
    }

    课外知识:
    (1)为循环打印出的控件绑定单击事件
    private Random _random = new Random();
    private void DrawMap()
    {
    for(int i=0;i<10;i++)
    {
    for (int j = 0; j < 10; j++)
    {
    //实例化图片框
    PictureBox pic = new PictureBox();
    //显示图片的样式
    pic.SizeMode = PictureBoxSizeMode.StretchImage;
    //随机产生图片,0-5之间
    tag = _random.Next(1,7);
    //设置图片宽度和高度
    pic.Size = new Size(_width, _width);
    //确定坐标
    pic.Location = new Point(_offX + i * _width, _offY + j * _width);
    //加载图片
    pic.Image = Image.FromFile("img/" + _tag + ".gif");
    //记录图片编号
    pic.Tag = _tag;
    //绑定pic的click事件,按Tab键两次可出现下面的事件
    pic.Click += new EventHandler(pic_Click);
    //把图片框动态加载到页面
    this.Controls.Add(pic);
    //将图片加到数组
    _pings[i, j] = pic;
    }
    }
    }


    void pic_Click(object sender, EventArgs e)
    {
    }

    (2)可让btnRefresh控件又执行一次操作,相当于调用已经存在的事件
    this.btnRefresh.PerformClick();

    (3)当执行一个事物的时候,让另一个事物停止的方法
    在要停止另一个事物的事物里面写 //要停止的事物的名称
    this.btnStart.Click -= new System.EventHandler(this.btnStart_Click);

    (4)播放声音:
    using System.Media;
    using System.Threading;

    //窗体正在退出的时候发生播放声音的事件
    private void Form1_FormClosing(object sender, FormClosingEventArgs e)
    {
    SoundPlayer sp = new SoundPlayer("sound\Windows XP 关机.wav");
    sp.Play();
    Thread.Sleep(2000);
    }

    (5) //在当前窗体中打开运行命令
    private void tsmiYunXing_Click(object sender, EventArgs e)
    {
    Help.ShowHelp(this, "C:\WINDOWS\system32\cmd.exe");
    }

    (6) //设置字体的样式
    private void cboFont_SelectedIndexChanged(object sender, EventArgs e)
    {
    this.txtContent.Font= new Font(this.cboFont.Text,12);
    }

    //将txtContent中的字体加粗
    private void label1_Click(object sender, EventArgs e)
    {
    this.txtContent.Font = new Font(this.cboFont.Text, 12,FontStyle.Bold);
    }

    (7)打开一个窗口,让用户选择路径,并获得用户选择的路径(弹出一个窗口):
    folderBrowserDialog1.ShowDialog();
    txtPath.Text = folderBrowserDialog1.SelectedPath;

    (8)将一个控件的背景颜色设置为用户自定义的颜色(弹出一个窗口):
    colorDialog1.ShowDialog();
    this.txtPath.BackColor = colorDialog1.Color;

    (9)设置一个txtPath文本框中的字体(弹出一个窗口):
    fontDialog1.ShowDialog();
    this.txtPath.Font = fontDialog1.Font;

    (10)打开一个保存内容的对话框(弹出一个窗口):
    saveFileDialog1.ShowDialog() ;
    txtPath.Text = saveFileDialog1.FileName;

    (11)窗体的AcceptButton属性中设置一个btnSearch,则不管用户在哪里按回车键,程序自动调用btnSearch按钮的点击事件

    (12)彻底的隐藏当前的窗体,在程序的Application.Exit();事件中隐藏资源释放
    this.Hide();

    (13)设置窗体的可见度:
    this.Opacity = this.Opacity - 0.02;

    (14)获取当前的系统时间:
    DateTime time = DateTime.Now;
    txtPath.Text = time.ToString() ;

    (15)求两个时间的差:
    DateTime TimeEnd = DateTime.Now;
    DateTime TimeEnd = DateTime.Now;
    TimeSpan TimeStartToEnd = TimeEnd.Subtract(TimeStart);

    (16)//绘制格子
    private void frmGraphics_Paint(object sender, PaintEventArgs e)
    {
    for (int i = 0; i < 17; i++)
    {
    for (int j = 0; j < 15; j++)
    {
    e.Graphics.DrawLine(new Pen(Color.YellowGreen, 1), new Point(i * 30, j * 30), new Point(400, j * 30));
    e.Graphics.DrawLine(new Pen(Color.YellowGreen, 1), new Point(i * 30, j * 30), new Point(i * 30, 400));
    }
    }
    }

    (17)获取一个应用程序下的所有文件名称,不包括可执行文件的名称
    private void FrmSelectMaps_Load(object sender, EventArgs e)
    {
    string[] files = Directory.GetFiles(Application.StartupPath + "/maps", "*.bin");
    foreach (string str in files)
    {
    lstMaps.Items.Add(str.Substring(str.Length - 7,3));
    }
    }

    (18)循环删除类型为PictureBox的控件
    for (i = this.Controls.Count - 1; i >= 0; i--)
    {
    if (this.Controls[i] is PictureBox)
    {
    Control ctrl = this.Controls[i];
    this.Controls.RemoveAt(i);
    ctrl.Dispose();
    }
    }
    注意:不能用foreach删除,应为用foreach的前提是不能改变集合中的数据,只能打印信息或者查找信息

    (19)可实现类和类之间的参数传递,相当于一个项目中的全局变量
    Program.MapName = this.lstMaps.SelectedItem.ToString();

    (20)在label.font=new System.Drawing.Font("宋体",14.25F, System.Drawing.FontStyle.regular,System.Drawing.GraphicsUnit.Point,((byte)(134)));
    label.TextAlign = ContentAlignment.MiddleCenter;

    (21)App.config文件的应用:
    1.引入System.Configuration;
    2.using System.Configuration;
    3.string strConn=ConfigurationManager.AppSettings["ylconn"];
    在App.config中写:
    <configuration>
    <appsettings>
    <add key="ylconn" value="数据库连接字符串">
    </appsettings>
    </configuration>

    (22)委托:委托类型的变量可以接受的数值只能是一个函数,即接受的值是一个方法的地址
    public delegate int MathOptDelegate(int value1,int value2);
    MathOptDelegate oppDel;
    MathOpt obj=new MathOpt();
    oppDel=obj.Add;
    Console.WriteLine(oppDel(1,2));

    public int Add(int a,int b)
    {
    return a+b;
    }

    (23)ReferenceEquals():测试两个引用是否指向类的相同实例,即地址是否相同

    (24)抽象类:指示某个类只能是其它类的基类、抽象类不能实例化,可以有实例方法

    (25)异常处理:ex包含的属性:
    ex.HelpLink="我的帮助文档.txt"; 当出现异常时,连接到帮助文档上,以提供更多的异常信息
    ex.Source="我的程序"; 导致异常的应用程序或对象名
    ex.TargetSite 抛出异常的方法名
    ex.StackTrace 堆栈上方法调用的信息
    ex.Message 提供文本,该文本描述了错误情况

    (26)char数组转换成字符串:
    可通过字符串的构造函数来完成 String(char[])和String(char[],int,int)
    char[] tcs={'t','e','s','t','m','e'}
    string tstr=new string(tcs);
    Console.WriteLine(tstr);

    (27)获取字符串中的单个字符
    char ch=tstr[3]; Console.WriteLine(ch);//输出t

    (28)
    委托和事件
    委托: 类
    关键字:delegate
    含义:相同签名的方法[方法参数, 返回值]的抽象
    委托三个步骤
    A: 定义委托
    B: 实例化委托
    C: 调用委托

    事件: 特殊的委托
    关键字:event
    三个步骤
    A: 定义事件
    B: 订阅事件
    C: 触发事件

    问题:
    1: 不清楚事件应该定义在哪里
    如果A类要调用B类的方法或控制B类的控件
    在A类中定义和触发事件,在B中订阅事件
    2: 在哪里订阅事件

    例子:
    namespace DemoDele
    {
    public partial class frmChild : Form
    {
    public frmChild()
    {
    InitializeComponent();
    }

    //定义委托
    public delegate void DeleSendInfo(string info);

    //定义事件
    public event DeleSendInfo OnSendInfo;

    private void button1_Click(object sender, EventArgs e)
    {
    //触发事件
    if (OnSendInfo != null)
    OnSendInfo(this.textBox1.Text);
    }
    }
    }

    namespace DemoDele
    {
    public partial class frmMain : Form
    {
    public frmMain()
    {
    InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
    frmChild frm = new frmChild();
    //订阅事件
    frm.OnSendInfo += new frmChild.DeleSendInfo(frm_OnSendInfo);
    frm.ShowDialog();
    }

    void frm_OnSendInfo(string info)
    {
    this.listBox1.Items.Add(info);
    }
    }
    }

    (29)泛型方法和泛型类
    namespace 泛型类和泛型方法
    {
    class Program
    {
    static void Main(string[] args)
    {
    //XML序列化和反序列化
    Student stu1 = new Student("A", 12);
    MySeri<Student>.XmlSeri(stu1,"234.bin");
    Student stu4 = MySeri<Student>.XmlDesSeri("234.bin");
    Console.WriteLine(stu4.Name);
    return;
    //二进制序列化和反序列化
    MySeri<Student>.BinarySeri(stu1,"123.bin");
    Student stu3 = MySeri<Student>.BinaryDesSeri("123.bin");
    Console.WriteLine(stu3.Name);

    return;
    Student stu2 = new Student("B", 13);
    int result = Compare<Student>(stu1, stu2);
    Console.WriteLine(result);
    }

    /// <summary>
    /// 泛型方法
    /// </summary>
    static int Compare<T>(T i, T j) where T : IComparable<T>
    {
    return i.CompareTo(j);
    }
    }

    [Serializable]
    public class Student : IComparable<Student>
    {
    public Student() { }

    public Student(string name, int age)
    {
    this._name = name;
    this._age = age;
    }
    private string _name;
    /// <summary>
    /// 姓名
    /// </summary>
    public string Name
    {
    get { return _name; }
    set { _name = value; }
    }

    private int _age;
    /// <summary>
    /// 年龄
    /// </summary>
    public int Age
    {
    get { return _age; }
    set { _age = value; }
    }

    public int CompareTo(Student other)
    {
    return this.Name.CompareTo(other.Name);
    }

    }

    //泛型类
    class MySeri<T> where T : class, new()
    {
    //二进制序列化
    public static void BinarySeri(T t, string fileName)
    {
    using (FileStream fs = new FileStream(fileName, FileMode.Create))
    {
    BinaryFormatter bf = new BinaryFormatter();
    bf.Serialize(fs, t);
    }
    }

    //二进制反序列化
    public static T BinaryDesSeri(string fileName)
    {
    using (FileStream fs = new FileStream(fileName, FileMode.Open))
    {
    BinaryFormatter bf = new BinaryFormatter();
    return (T)bf.Deserialize(fs);
    }
    }

    //XML序列化
    public static void XmlSeri(T t, string fileName)
    {
    using (FileStream fs = new FileStream(fileName, FileMode.Create))
    {
    XmlSerializer xs = new XmlSerializer(typeof(T));
    xs.Serialize(fs, t);
    }
    }

    //XML反序列化
    public static T XmlDesSeri(string fileName)
    {
    using (FileStream fs = new FileStream(fileName, FileMode.Open))
    {
    XmlSerializer xs = new XmlSerializer(typeof(T));
    return (T)xs.Deserialize(fs);
    }
    }

    }

    (30)字符串转换为int,经典写法:
    string str=Console.ReadLine();
    int i;
    bool right=int.TryParse(str,out i);
    if(right)
    Console.WriteLine(i);
    else
    Console.WriteLine("error");

  • 相关阅读:
    Swift
    Swift
    Swift
    Swift
    Swift
    Swift
    Swift
    将Ojective-C代码移植转换为Swift代码
    Swift
    房费制——报表(1)
  • 原文地址:https://www.cnblogs.com/Bonker/p/3540864.html
Copyright © 2011-2022 走看看