##一、描述
此文章描述一下C#的一些基础知识##二、基础知识
#####词典:其实就是一个Map集合,需要导入
//创建一个词典using System.Collections.Generic;Dictionarymap = new Dictionary ();//添加键值对map.Add ("name1", "name1.txt");map.Add ("name2", "name2.txt");map.Add ("name3", "name3.txt");map.Add ("name4", "name4.txt");//输出对应键的值Console.WriteLine ("outPut:"+map["name3"]);复制代码
#####获取某个方法执行的时间
Stopwatch timer = new Stopwatch(); timer.Start(); test(); timer.Stop(); Console.WriteLine("write:" + timer.ElapsedMilliseconds); //这里会输出方法执行用了多少时间复制代码
#####抽线类,实现需要加入override
//实现抽象类class Student :OnClickListener{ private String myclass; public Student(String name, String age, String myclassName) { this.myclass = myclassName; } public void getMyClassName() { Console.WriteLine(myclass); } //运用override来实现抽线类的方法 public override void getMessage() { Console.WriteLine("DDDD"); } } //抽线类 abstract class OnClickListener { public abstract void getMessage(); }复制代码
#####重写基类方法(虚方法):需要重写基类的一个方法的时候,需要用virtual 和override 方法进行定义,这样才可以重写基类的方法。
class Student : Person { public override void GetMyName() { Console.WriteLine("User"); } } class Teacher : Person { public override void GetMyName() { Console.WriteLine("Teacher"); } } //基类Person,拥有一个虚方法GetMyName class Person { public virtual void GetMyName() { Console.WriteLine("Person"); } }复制代码
#####Model类的get和set方法
class Person { private String name; public String Name { get { return name; } set { name = value; } } } //抽象Get和Set public abstract class Person { public abstract string Name { get; set; } public abstract int Age { get; set; } }复制代码
#####类增加索引器(可以存在多个索引器,只要参数存入的参数类型不同就好)
class MyList { static public int size = 10; private string[] namelist = new string[size]; public string this[int index] { get { if (index >= 0 && index < namelist.Length - 1) { return namelist[index]; } return ""; } set { if (index >= 0 && index < namelist.Length - 1) { namelist[index] = value; } } } } MyList mylist = new MyList(); mylist[0] = "123"; mylist[1] = "321"; for (int i = 0; i < MyList.size; i++) { Console.WriteLine(mylist[i]); }复制代码
####委托
delegate int NumberChanger(int n);namespace DelegateAppl{ class TestDelegate { static int num = 10; public static int AddNum(int p) { num += p; return num; } public static int MultNum(int q) { num *= q; return num; } public static int getNum() { return num; } static void Main(string[] args) { // 创建委托实例 NumberChanger nc1 = new NumberChanger(AddNum); NumberChanger nc2 = new NumberChanger(MultNum); // 使用委托对象调用方法 nc1(25); Console.WriteLine("Value of Num: {0}", getNum()); nc2(5); Console.WriteLine("Value of Num: {0}", getNum()); Console.ReadKey(); } }}复制代码