C# Generics
Array: (需要一队数据,他们由index控制)
1:内存中的样子
2:Array定义方法:
int[] myArrays = new Int[4];
myArrays[0] = 100;
myArrays[1] = 200;
myArrays[2] = 300;
myArrays[3] = 200;
or
int[] myArrays = {100,200,300,200};
string[] myStrings = {"one", "two", "three","four"};
3:Multi-Array定义方法:
int[,] multiArray = new int[3,3];
multiArray[0,1] = 10;
......
or
int[,] multiArray = new int[,]{
{0,1,2},
{3,4,5},
{6,7,8}
};
4: some array build-in features:
int[] myArray = {100,200,300,400};
myArray.GetLength(); //return 4
myArray.Clear(myArray,0,4); //starting at 0, clears 4 elements
myArray.Sort(myArray); //sort the given array
myArray.Reverse(myArray); //reverse the given array
5:array也是reference type
int [] myArray = {1,18,745,34,16,94,29,3,19,200};
int[] otherArray = myArray;
otherArray[3] = 15;
Console.WriteLine("The fourth number is {0}", myArray[3]); //输出为15,因为otherArray和myArray指向的是同一内存地址
ArrayList:(Dynamic Array + Mixed Content)
1:Create ArrayList
ArrayList myAL = new ArrayList();
ArrayList myAL = new ArrayList(10);
ArrayList myAL = new ArrayList(); //each of underline items add as Object myAL.Add("one"); myAL.Add(2); myAL.Add("Hello"); myAL.Add(42);
2: Adding/Removing
myAL.Add(object item);
myAL.Insert(int index, object item); 比较: myAL[0] = "hello" //一般还是用arrayList提供的方法设值好
myAL.Remove(object item);
myAL.RemoveAt(int index);
myAL.Count;
3: 有关loop:
ArrayList myAL = new ArrayList();
myAL.Add("item 1");
myAL.Add("item 2");
myAL.Add("item 3");
myAL.Add("item 4");
foreach (object obj in myAL) 比较: for(int i=0; i<myAL.count; i++)
myAL的数据类型 Collection {
{ Console.WriteLine("{0}, myAL[i]");
Console.WriteLine("{0}, obj"); }
}
4: 灵活使用ArrayList
using System.Collections; //check class 里是否有这个NS ...... ArrayList myAL = new ArrayList; //看ArrayList前面没有类型修饰符,所以接受任何object myAL.Add("one"); myAL.Add("two"); myAL.Add(3); myAL.Add(4); myAL.Insert(0,1.25f); foreach(object obj in myAL) { if(obj is int) COnsole.WriteLine("{0}", obj); //输出1.25,3,4 }
Stacks: Last in, First out 麦当劳汉堡(需要一队数据,他们排列的顺序与进入的顺序相反)
using System.Collections; //check class 里是否有这个NS
......
Stacj myStack = new Stack(); myStack.Push("string 1"); //看Stack前面没有类型修饰符,所以接受任何object myStack.Push("string 2"); object obj = myStack.Pop(); //gets top value object obj = myStack.Peek(); //looks at top myStack.Clear(); //get rid of everything
int c = myStack.Count; //gets the number of items in the stack
Queue: First In First Out 柜台办理手续(需要一队数据,他们排列的顺序与进入的顺序相同)
Queue myQ = new Queue(); myQ.Enqueue("item1"); myQ.Enqueue("item2"); myQ.Enqueue("item3"); myQ.Enqueue("item4"); Console.WriteLine("There are {0} items in the Queue", myQ.Count); while(myQ.count > 0){ string str = (string)myQ.Dequeue(); //Dequeue最上面一个出,其实object类型,需要casting Console.WriteLine("Dequeueing object {0}", str); }
泛型:
泛型即<type>。
创建int[], Strings[]类会很繁琐。
常见统一object[]类会有casting和放入类型无限制的坏处。
Generics is a clever way for you to make "generic" classes when you create the class ("create" as in, write the code to define the class, not actually creating an instance of the class), and then when you want to use them, you simply state which type you want to use at the time. So one time, you'll use the generic class and say "this time it is a list of ints", and another time, you'll say "now I want to make a list of Player objects".
In short, generics provide a way to create type safe classes, without having to actually commit to any particular type when you create the class.
List<type>
1 List<string> strings = new List<string>(); 2 strings.Add("text1"); 3 strings.Add("text2");
1 //push other front item back, start from 0 2 3 strings.Insert(0, "text3");
其他方法:http://rbwhitaker.wikidot.com/c-sharp-using-generics
Dictionaries:有关associated data的数据结构
1:key是唯一的
2:key可以是object对应的值也可以是object,一般我们给int,double,string等简单的类型
在使用普通list<T>情况下为了让void Main部分主程序看起来简单,我们要写自己的方法来add,get,display每一个List<Person>.
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Threading.Tasks; 6 7 namespace ConsoleApplication4 8 { 9 class Person 10 { 11 public int Id { get; private set; } 12 public string Name { get; private set; } //constracter给property赋值,比较下面 13 public Person(int id, string name) 14 { 15 Id = id; 16 Name = name; 17 } 18 } 19 class People 20 { 21 private List<Person> _people; 22 public People() //constracter给filed赋值 23 { 24 _people = new List<Person>(); 25 } 26 public void AddPerson(Person person) 27 { 28 _people.Add(person); 29 } 30 public Person GetPersonById(int id) 31 { 32 foreach (var person in _people) 33 { 34 if (person.Id == id) 35 { 36 return person; 37 } 38 } 39 return null; //不知道返回什么就返回null 40 } 41 public void DisplayPeople() 42 { 43 foreach (var person in _people) 44 { 45 Console.WriteLine("{0} - {1}", person.Id, person.Name); 46 } 47 } 48 } 49 class Program 50 { 51 static void Main(string[] args) 52 { 53 var people = new People(); 54 people.AddPerson(new Person(423, "Nelson")); 55 people.AddPerson(new Person(233, "shawn")); 56 people.AddPerson(new Person(443, "chris")); 57 people.AddPerson(new Person(133, "rebecca")); 58 people.AddPerson(new Person(533, "mandy")); 59 people.DisplayPeople(); 60 Console.Write("Selected People:"); 61 var selectedId = int.Parse(Console.ReadLine()); 62 var person = people.GetPersonById(selectedId); 63 Console.WriteLine("You selected {0}", person.Name); 64 Console.ReadLine(); 65 } 66 } 67 }
换成Dictionary后程序变的简单多了,而且更灵活更少代码
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Threading.Tasks; 6 7 namespace ConsoleApplication4 8 { 9 class Person 10 { 11 public int Id { get; private set; } 12 public string Name { get; private set; } //constracter给property赋值,比较下面 13 public Person(int id, string name) 14 { 15 Id = id; 16 Name = name; 17 } 18 } 19 /* 20 class People 21 { 22 private List<Person> _people; 23 public People() //constracter给filed赋值 24 { 25 _people = new List<Person>(); 26 } 27 public void AddPerson(Person person) 28 { 29 _people.Add(person); 30 } 31 public Person GetPersonById(int id) 32 { 33 foreach (var person in _people) 34 { 35 if (person.Id == id) 36 { 37 return person; 38 } 39 } 40 return null; //不知道返回什么就返回null 41 } 42 public void DisplayPeople() 43 { 44 foreach (var person in _people) 45 { 46 Console.WriteLine("{0} - {1}", person.Id, person.Name); 47 } 48 } 49 } 50 * */ 51 class Program 52 { 53 static void Main(string[] args) 54 { 55 Dictionary<int, Person> people = new Dictionary<int, Person>(); 56 people.Add(442, new Person(442, "nelson")); 57 people.Add(142, new Person(142, "shawn")); 58 people.Add(542, new Person(542, "chris")); 59 people.Add(425, new Person(425, "rebecca")); 60 people.Add(134, new Person(134, "mandy")); 61 foreach (var person in people) 62 { 63 Console.WriteLine("{0} - {1}", person.Key, person.Value.Name); 64 } 65 Console.WriteLine("Selecte person"); 66 var selectedId = int.Parse(Console.ReadLine()); 67 var selectedPerson = people[selectedId]; 68 Console.WriteLine("You selected {0}", people[selectedId].Name); 69 Console.ReadLine(); 70 } 71 72 } 73 }
或者我们变list<>为dictionary,这个不用自己手动加key,key和输入的person的ID一样。
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Threading.Tasks; 6 7 namespace ConsoleApplication4 8 { 9 class Person 10 { 11 public int Id { get; private set; } 12 public string Name { get; private set; } //constracter给property赋值,比较下面 13 public Person(int id, string name) 14 { 15 Id = id; 16 Name = name; 17 } 18 } 19 20 class People 21 { 22 private Dictionary<int, Person> _people; 23 public People() //constracter给filed赋值 24 { 25 _people = new Dictionary<int,Person>(); 26 } 27 public void AddPerson(Person person) 28 { 29 _people.Add(person.Id, person); 30 } 31 public Person GetPersonById(int id) 32 { 33 return _people[id]; //如果希望throw exception用这个 34 35 /* 如果不希望找不到key后throw exception,用这个这不到的话返回null,person可以是null 36 * 37 Person person; 38 if (_people.TryGetValue(id, out person)) 39 { 40 return person; 41 } 42 return null; 43 */ 44 } 45 public void DisplayPeople() 46 { 47 foreach (var person in _people) 48 { 49 Console.WriteLine("{0} - {1}", person.Key, person.Value.Name); 50 } 51 } 52 } 53 54 class Program 55 { 56 static void Main(string[] args) 57 { 58 var people = new People(); 59 people.AddPerson(new Person(423, "Nelson")); 60 people.AddPerson(new Person(233, "shawn")); 61 people.AddPerson(new Person(443, "chris")); 62 people.AddPerson(new Person(133, "rebecca")); 63 people.AddPerson(new Person(533, "mandy")); 64 people.DisplayPeople(); 65 Console.Write("Selected People:"); 66 var selectedId = int.Parse(Console.ReadLine()); 67 var person = people.GetPersonById(selectedId); 68 Console.WriteLine("You selected {0}", person.Name); 69 Console.ReadLine(); 70 } 71 72 } 73 }
另外一个例子:
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Threading.Tasks; 6 7 namespace ConsoleApplication2 8 { 9 class Program 10 { 11 12 static void Main(string[] args) 13 { 14 Dictionary<string, string> words = new Dictionary<string, string>(); 15 while (true) 16 { 17 Console.WriteLine("----------------"); 18 Console.WriteLine("Add <word>"); 19 Console.WriteLine("Define <word>"); 20 Console.WriteLine("----------------"); 21 22 var input = Console.ReadLine(); 23 var parts = input.Split(' '); 24 25 if (parts.Length != 2) 26 { 27 continue; 28 } 29 if (parts[0] == "add") 30 { 31 Console.Write("Define {0}", parts[1]); 32 var defineition = Console.ReadLine(); 33 words.Add(parts[1], defineition); 34 } 35 else if (parts[0] == "define") 36 { 37 string value; 38 if (!words.TryGetValue(parts[1], out value)) 39 //判断key在不在字典里,在的话整个返回为1,并且返回输入的值到value,不在的话整个返回0,value为null 40 { 41 Console.WriteLine("I don't know what a {0} is", parts[1]); 42 continue; 43 } 44 Console.WriteLine("{0} = {1}", parts[1], value); 45 } 46 } 47 } 48 } 49 }
使用Key前先判断:
1 // When a program often has to try keys that turn out not to 2 // be in the dictionary, TryGetValue can be a more efficient 3 // way to retrieve values. 4 string value = ""; 5 if (openWith.TryGetValue("tif", out value)) 6 { 7 Console.WriteLine("For key = \"tif\", value = {0}.", value); 8 } 9 else 10 { 11 Console.WriteLine("Key = \"tif\" is not found."); 12 } 13 14 15 ... 16 17 18 // The indexer throws an exception if the requested key is 19 // not in the dictionary. 20 try 21 { 22 Console.WriteLine("For key = \"tif\", value = {0}.", 23 openWith["tif"]); 24 } 25 catch (KeyNotFoundException) 26 { 27 Console.WriteLine("Key = \"tif\" is not found."); 28 }
The upper example shows how to use the TryGetValue method as a more efficient way to retrieve values in a program that frequently tries keys that are not in the dictionary. For contrast, the example also shows how the Item property (the indexer in C#) throws exceptions when attempting to retrieve nonexistent keys.
注意people.Add(42, new person(42, "nelson"));这句话,第一个42实际上是index,如果和后面一样的话就可以在后面的判断上很简单,省去很多if,else判断。
判断最好不要用ContainsKey而是用TryGetValue方法:
var test = Console.ReadLine(); if(words.ContainsKey("test")) Console.WriteLine(words["test"]);
因为他会看两次key,另外看上去ugly
注意dictionary还有很多别的方法,和两个property,words.Key words.Values,他们都是集合,所有的key和value的集合。
所以可以写成
foreach(var key in words.Keys) { Console.WriteLine("I know what a {0} is!", key); }