C#学习笔记- 浅谈数组复制,排序,取段,元组

C#学习笔记- 浅谈数组复制,排序,取段,元组

using System;
using System.Collections.Generic;

namespace Application
{
class Test
{
static void Main ()
{

//元组类型Tuple是静态类型,用静态方法创建实例,超过8个元素则第8个元素是元组类型

var tupe = Tuple.Create (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对数组取段====
var segments = new ArraySegment (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接口

//======或写一个附加类并实现Comparer接口
public enum PersonCompareType
{
firstName,
lastName
}

public class PersonComparer:IComparer
{
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#学习笔记- 浅谈数组复制,排序,取段,元组就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持脚本之家。

你可能感兴趣的:(C#学习笔记- 浅谈数组复制,排序,取段,元组)