繁体   English   中英

在C#中创建新的数组类型

[英]Create a new type of array in C#

是否可以在C#中从现有类型创建新类型。 这在C语言中很容易实现,但是我无法弄清楚在C#中是如何完成的。 像这样:

type Map int[,]

据我所知,不,也不。

遗产

您不能从数组类型继承。

引用C#5.0规范的10.1.4.1节,

类类型的直接基类不能为以下任何类型: System.ArraySystem.DelegateSystem.MulticastDelegateSystem.EnumSystem.ValueType 此外,泛型类声明不能将System.Attribute用作直接或间接基类。

我能想到的最接近的方法是添加扩展方法,但这当然不是您想要的。

别名

别名可以设置使用using的代码文件的顶部指令:

using Map = System.Int32;

但是据我所知,这不支持数组类型。

根据C#5.0规范的第9.4.1节, using别名看起来像,

使用标识符=名称空间或类型名称;

namespace-or-type-name在3.8节中定义,并且未提及任何有关数组类型的内容。

如果您的唯一目的是“使用Map而不是int [,]”,则可以创建带有索引属性的Map类

public class Map
{
  private int[,] _map;

  public Map(int rows, int columns)
  {
    // rows, columns validation here
    _map = new int[rows, columns];
  }

  public int this[int r, int c]
  {
    get { return _map[r,c]; }
    set { _map[r,c] = value; }
  }
}

不如type Map int[,]那么短,但是可以提供所需的结果。 例:

Map m = new Map(4,4);
m[2,2] = 1;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM