1.代码
1.1 main 部分(Program.cs)
static void Main()
{
string[,] array = new string[3, 4];
for (int i = 0; i < array.GetLength(0); i++)
{
for (int j = 0; j < array.GetLength(1); j++)
{
array[i, j] = i.ToString() + j.ToString();
}
}
string[] result = DoubleArrayHelper.GetElements(array,2,0,Direction.Right,5);
}
1.2 Direction 部分(Direction.cs)
class Direction//引用类型
{
private int rIndex;
public int RIndex
{
get { return this.rIndex; }
set { this.rIndex = value; }
}
public int CIndex { get; set; }
public Direction() { }
public Direction(int rIndex,int cIndex)
{
this.rIndex = rIndex;
this.CIndex = cIndex;
}
public static Direction Up
{
get { return new Direction(-1,0); }
}
public static Direction Down
{
get { return new Direction(1, 0); }
}
public static Direction Left
{
get { return new Direction(0, -1); }
}
public static Direction Right
{
get { return new Direction(0, 1); }
}
}
1.3 获取二维数组部分(DoubleArrayHelper.cs)
class DoubleArrayHelper
{/// <summary>
/// 获取二维数组元素
/// </summary>
/// <param name="array">二维数组</param>
/// <param name="rIndex">行索引</param>
/// <param name="cIndex">列索引</param>
/// <param name="dir">方向</param>
/// <param name="count">数量</param>
/// <returns>所有满足条件的元素</returns>
public static string[]GetElements(string[,]array,int rIndex,int cIndex,Direction dir,int count)
{
List<string> result = new List<string>(count);
for (int i = 0; i < count; i++)
{
rIndex += dir.RIndex;
cIndex += dir.CIndex;
if (rIndex >= 0&&rIndex<array.GetLength(0)&&cIndex>=0&&cIndex<array.GetLength(1))
result.Add(array[rIndex,cIndex]);
}
return result.ToArray();
}
}
2.调试示例
返回了所需数组元素的索引
3.小结
3.1静态
3.1.1成员变量
静态(static关键字修饰)成员变量属于类,类被加载时初始化,且只有一份;(饮水机)
实例对象属于对象,在每个对象被创建时初始化。每个对象一份。(杯子)
静态特点:存在优先于对象,被所有对象所共享,常驻内存。
3.1.2构造函数
实例构造函数:提供创建对象的方式,初始化类的实例数据成员
静态构造函数:初始化类的静态数据成员,仅在类加载时调用一次。
3.1.3方法
静态代码块只能访问静态成员
正常解释:静态方法在外部调用时写的是根据类而不是对象,所以如果静态方法里有实例变量的话编译器就不知道这个实力变量是哪个类的成员。实例方法是共用的,用对象去点(object.xxxx)就是告诉他到底是谁在用这个共用的东西。
通俗解释:静态出现比实例早,早出现的没法调用晚出现的(创建时间不同)
实例代码块则都可以访问。
3.1.4适用性
1.所有对象需要共享的数据(例如同一地图上的资源更新)
2.工具类
3.没对象前访问成员(例如想得知创建了多少个对象)
3.2结构和类的区别
类(class):引用类型
结构(struct):用于封装小型相关变量的值类型,在栈上开辟空间,适用于轻量级对象,可节约资源。(struct结构自带无参数构造函数,所以不能包含无参数构造函数)
3.3关于常量
需要定义一个不能改变的量,用(const声明)常量