unity开发 --------- c# 基本语法 004

来源:互联网 发布:如何给mac本地装软件 编辑:程序博客网 时间:2024/06/02 06:45

关联类容

unity开发 --------- c# 基本语法http://blog.csdn.net/u012085988/article/details/19981161


1、简单数组

c#中的数组是一个引用类型,这也是他与c++中数组的本质区别。c#中数组存在堆中,c++中是在栈上。不过c#中的数组与c++中的指向数组的指针很相似:

int[] p = new int[10];     // c#int* p = new int[10];     // c++
c#中的数组封装有一些基本操作。如Length,迭代器等等。。。

c#中数组支持foreach语法

简单数组应用于引用类型时要注意为每个引用初始化,不然直接使用单个引用时会造成编译器报错。

Type [] p= new Type [10]for(int i = 0; i < p.Length; i++)    p[i] = new Type();

2、多维数组

int[ , ] p = new int[3,3];
维度间用逗号分开,上例为一个二维数组,以此类推,三维、思维数组也是用逗号分开。在c++中用[]分开每个维度。


3、锯齿数组

int[][] p = new int[3][];p[0] = new int[2];p[1] = new int[3];p[2] = new int[4];
多维数组的元素在堆上是连续的,而锯齿数组的元素并不是连续存储的。它只是将每个单独维度的元素连续存储。

锯齿数组实际上就是由多个维度不用的数组组成的数组。二维锯齿数组可以用c++中的int** p来实现。


4、ArraySegment<T>

c#中ArraySegment<T>是一个struct!unity并没有这个结构,所以要用它的话,就要自己实现它。该结构只需要三个字段 数组、起始索引、结束索引!


5、枚举

foreach语句中使用的就是枚举。实现了IEumerable接口的类就可以用foreach迭代了!

foreach ( var p in persons ){    wroteLine(p);}// 该语句会解析成下面的代码IEnumerator<Person> enumerator = persons.GetEnumerator();while(enumerator.MoveNext()){    Person p = enumerator.Current;    WriteLine(p);}

6、yield 语句

yield return语句返回一个元素。yield break停止迭代。

包含yield的语句的方法或属性被称为迭代块,迭代块必须声明为返回IEnumerator或IEnumerator的接口。这个块可以包含多个yield return语句或yield brake语句。但不能有return。yield语句会自动为我们生产一个枚举器:

string[] names = {"wmm", "ytt", "wm", "wtt"}public IEnumrator<string> GetEnumrator{    for(int i = 0; i < 4; i ++)    {        yield return names[i];    }}
调用GetEnumrator函数返回的并不是一个string,而是一个枚举器!这个枚举器是编译器根据函数内的代码自动生成的。有了这种机制,我们在用枚举器迭代某个容器时,就很方便了!编译器除了会自动为我们生成IEnumrator<T>,还能自动生成IEnumrable<T>。这样一来,我们连GetEnumrator函数都不用写了!太神奇了!!!!
public class myCol : IEnumerable<string>{private string[] names = {"wmm", "ytt", "wm", "wtt"};public IEnumerator<string> GetEnumerator (){for (int i = 0; i < 4; i++) {yield return names[i];}}}
实现了GetEnumerator方法后,myCol就可以用foreach来迭代了。但若不想让myCol实现IEnumerator接口,不想实现GetEnumrator函数可以用下面的代码,直接自动生成一个IEnumrable对象:

public class myCol{private string[] names = {"wmm", "ytt", "wm", "wtt"};public IEnumerable<string> reverse(){for (int i = 0; i < 4; i++) {yield return names[i];}}}
注意:函数返回值是IEnumerable而不是IEnumrator!!!


7、foreach 如何实现枚举

foreach 实现枚举,实际上是用一个枚举器IEnumrator。那么这个枚举器怎么来的呢?它来自IEnumrable接口的GetEnumrator函数。所以要使一个自定义类实现枚举,要么让该类实现IEnumrable接口,要么定义一个函数,让他返回一个IEnumrable对象。


8、元组 (Tuple)

Tuple<T>、Tuple<T1, T2>, Tuple<T1, T2, T3> ……

使用Tuple.Create<T1, T2, ...>(t1, t2...)来创建元组!






0 0