在C#中使用枚举值哨兵(在​​编译时枚举的大小)? [英] Using sentinal values in C# enum (size of enum at compile time)?

查看:292
本文介绍了在C#中使用枚举值哨兵(在​​编译时枚举的大小)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一个快捷方式我与嵌入的API打交道时用C经常使用(通信协议,主要是)让我来编辑枚举数组,并拥有一切大小后正确:

A shortcut I often use in C when dealing with embedded APIs (communications protocols, primarily) allows me to edit an enum array and have everything else sized correctly after that:

typedef enum {
   errortype1,
   errortype2,
   ...
   errortypeN,
   ERROR_TYPE_MAX
} ErrorTypeList;

int errorcounts[ERROR_TYPE_MAX]; // Create array to hold a counter for each error type

只要我添加新的错误类型之前ERROR_TYPE_MAX然后我就可以使用该值在其他地方给我的枚举的大小。

As long as I add new error types before ERROR_TYPE_MAX then I can use that value everywhere else to give me the size of the enum.

在C#中,然而,这不工作原样

In C#, however, this doesn't work as-is:

enum ErrorTypeList {
   errortype1,
   errortype2,
   ...
   errortypeN,
   ERROR_TYPE_MAX
};

int errorcounts[ErrorTypeList.ERROR_TYPE_MAX]; // Create array to hold a counter for each error type

本使用presents 数组大小不能在变量声明这表明使用指定的误差

This usage presents the error Array size cannot be specified in a variable declaration which suggests using new.

是定义在运行时数组(通过)我唯一的选择,或者是有办法做到这一点没有新的,因为枚举不是个大小ŧ去编译后改变?

Is defining the array at runtime (via new) my only option, or is there a way to accomplish this without a new, since the size of the enum isn't going to change after compilation?

有没有这种类型的枚举上浆模式的替代,更好地融入C#?

Is there an alternative to this type of enum sizing pattern that better fits into c#?

推荐答案

您将不得不使用

一个变量/字段声明没有指定数组的大小,当你构建阵列实例的唯一完成的。

A variable/field declaration does not specify the size of the array, that's only accomplished when you construct the array instance.

目前最可以指定数组多少维度都有,但不是每个维度的大小。

At most you can specify how many dimensions the array will have, but not the size of each dimension.

这篇关于在C#中使用枚举值哨兵(在​​编译时枚举的大小)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆