我正在使用一些代码,这些代码使用enumeration类的值(扩展uint8)来“按名称”而不是按硬编码数字访问矩阵列。采用这种方法的原因是,与允许命名字段访问的其他结构(例如结构/对象或表)相比,矩阵被认为具有更高的性能-据说可以在不牺牲性能的情况下提高代码的可读性。
麻烦的是,枚举类在包中找到,给它一个很长的名字。这极大地损害了可读性,以至于几乎破坏了“命名索引”的目的:% What it looks like without using an enum:
val = foo(:, 7); % Magic number, :(
% Current situation (the enum is called "somePackage.SomeMeaningfulCollectionEnum"):
val = foo(:, somePackage.SomeMeaningfulCollectionEnum.varName1); % Very long name, :(
% Desired solution:
E = somePackage.SomeMeaningfulCollectionEnum; % This throws an error in R2020a
val = foo(:, E.varName1); % Short and descriptive!
[尝试使用上面的“所需解决方案”时,出现以下错误:Error using somePackage.SomeMeaningfulCollectionEnum
Cannot call the constructor of 'somePackage.SomeMeaningfulCollectionEnum' outside of its enumeration block.
我想出了一种变通方法,其中包括将每个枚举成员存储在具有相同名称的struct字段中(请参阅my own answer below,但我想知道是否存在“适当”的方法来进行此操作。