亲宝软件园·资讯

展开

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

人气:0
想了解C#学习笔记- 浅谈数组复制,排序,取段,元组的相关内容吗,在本文为您仔细讲解C# 元组 数组的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:C#,元组,数组,下面大家一起来学习吧。

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

加载全部内容

相关教程
猜你喜欢
用户评论