C#学习笔记- 浅谈数组复制,排序,取段,元组
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
|
using System;
using System.Collections.Generic;
namespace Application
{ class Test
{ static void Main ()
{ //元组类型Tuple是静态类型,用静态方法创建实例,超过8个元素则第8个元素是元组类型 var tupe = Tuple.Create< int , int , string , string > (1, 2, "a" , "b" );
Console.WriteLine ( "{ 0},{ 1}" ,tupe.Item1, tupe.Item3);
//=====Array类是抽象类,只能通过它的静态方法CreateInstance()创建实例 //=====如果事先不知道类型,可以用此方法 Array arrays = Array.CreateInstance ( typeof ( int ), 5);
for ( int i = 0; i < arrays.Length; i++) {
arrays.SetValue (35, i); Console.WriteLine (arrays.GetValue (i)); } Person[] persons = { new Person { firstName = "su" , lastName = "uifu" },
new Person { firstName = "chen" , lastName = "xaohua" },
new Person { firstName = "cbb" , lastName = "ruifu" },
new Person { firstName = "utt" , lastName = "xiaohua" }
} ; //=====Clone()复制数组,引用类型复制索引值,值类型复制值 Person[] persons1 = persons.Clone (); Array.Sort (persons, new PersonComparer (PersonCompareType.lastName));
foreach (var p in persons) {
Console.WriteLine (p); } //======ArraySegment<T>对数组取段==== var segments = new ArraySegment<Person> (persons, 1, 2);
for ( int i = segments.Offset; i < segments.Offset + segments.Count; i++) {
Console.WriteLine (segments.Array [i]); } } public class Person
{ public string firstName{ get ; set ; }
public string lastName{ get ; set ; }
public override string ToString ()
{ return String.Format ( "{ 0},{ 1}" , firstName, lastName);
} } //======要对引用类型的数组使用Array.sort()方法,必须对类实现IComparable<T>接口 //======或写一个附加类并实现Comparer<T>接口 public enum PersonCompareType
{ firstName, lastName } public class PersonComparer:IComparer<Person>
{ private PersonCompareType pct;
public PersonComparer (PersonCompareType pct)
{ this .pct = pct;
} public int Compare(Person x,Person y)
{ if (x == null )
throw new ArgumentNullException ();
if (y == null )
throw new ArgumentNullException ();
switch (pct) {
case PersonCompareType.firstName:
return x.firstName.CompareTo (y.lastName);
case PersonCompareType.lastName:
return x.lastName.CompareTo (y.lastName);
default :
throw new ArgumentException ( "no.." );
} } } } |
以上这篇C#学习笔记- 浅谈数组复制,排序,取段,元组就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持服务器之家。