C#學(xué)習(xí)筆記- 淺談數(shù)組復(fù)制,排序,取段,元組
更新時間:2016年08月21日 15:00:48 投稿:jingxian
下面小編就為大家?guī)硪黄狢#學(xué)習(xí)筆記- 淺談數(shù)組復(fù)制,排序,取段,元組。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
C#學(xué)習(xí)筆記- 淺談數(shù)組復(fù)制,排序,取段,元組
using System;
using System.Collections.Generic;
namespace Application
{
class Test
{
static void Main ()
{
//元組類型Tuple是靜態(tài)類型,用靜態(tài)方法創(chuàng)建實(shí)例,超過8個元素則第8個元素是元組類型
var tupe = Tuple.Create<int,int,string,string> (1, 2, "a", "b");
Console.WriteLine ("{ 0},{ 1}",tupe.Item1, tupe.Item3);
//=====Array類是抽象類,只能通過它的靜態(tài)方法CreateInstance()創(chuàng)建實(shí)例
//=====如果事先不知道類型,可以用此方法
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()復(fù)制數(shù)組,引用類型復(fù)制索引值,值類型復(fù)制值
Person[] persons1 = persons.Clone ();
Array.Sort (persons, new PersonComparer (PersonCompareType.lastName));
foreach (var p in persons) {
Console.WriteLine (p);
}
//======ArraySegment<T>對數(shù)組取段====
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);
}
}
//======要對引用類型的數(shù)組使用Array.sort()方法,必須對類實(shí)現(xiàn)IComparable<T>接口
//======或?qū)懸粋€附加類并實(shí)現(xiàn)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#學(xué)習(xí)筆記- 淺談數(shù)組復(fù)制,排序,取段,元組就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
C# 二進(jìn)制數(shù)組與結(jié)構(gòu)體的互轉(zhuǎn)方法
本文將和大家介紹 MemoryMarshal 輔助類,通過這個輔助類用來實(shí)現(xiàn)結(jié)構(gòu)體數(shù)組和二進(jìn)制數(shù)組的相互轉(zhuǎn)換,對C# 二進(jìn)制數(shù)組與結(jié)構(gòu)體的互轉(zhuǎn)方法感興趣的朋友一起看看吧2023-09-09
C# .NET中Socket簡單實(shí)用框架的使用教程
最近一個項(xiàng)目因?yàn)橐玫絊ocket傳輸問題,所以決定學(xué)習(xí)一下,將自己學(xué)習(xí)的內(nèi)容總結(jié)分享出來,下面這篇文章主要給大家介紹了關(guān)于C# .NET中Socket簡單實(shí)用框架使用的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),需要的朋友可以參考下。2017-09-09

