首页 > 编程 > C# > 正文

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

2020-01-24 01:00:52
字体:
来源:转载
供稿:网友

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

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

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表