Case insensitive enumeration class

7 ビュー (過去 30 日間)
Phillip
Phillip 2016 年 9 月 19 日
編集済み: Sean de Wolski 2016 年 9 月 20 日
Hi,
How does one create a case insensitive enumeration class?
So that one could call it as:
aRed = colourEnum.RED;
aRed = colourEnum.red;
aRed = colourEnum.ReD;
I would also like to confirm that enumerations must follow variable naming conventions. Ie you can't have an enum that is:
enumclass.A/B
Am I right in this?
Regards, Phillip

採用された回答

Brendan Hamm
Brendan Hamm 2016 年 9 月 19 日
Why would you want to have your enumeration be able to have any case?
The only place I could consider this, is if the user has to specify the string via some form of text input e.g. an inputdlg. If this is the case, then you should simply do a case insensitive string validation and with this result dynamically create your object:
val = validatestring('red',{'Red'})
aRed = colourEnum.(val)
Other than this, the MATLAB command prompt will alert the user of the correct case of the characters involved.
Yes. Enumerations must conform to the MATLAB variable naming convention.
  1 件のコメント
Phillip
Phillip 2016 年 9 月 19 日
Hi Brendan
I hear you and I think you are right (need to give it some thought). The enumeration is unique in itself and should be treated as such. The only problem I have is that I need to code that validation outside of the enumeration object, where somehow naturally i wanted to do it within the object (so that the object handles it). Ie RED is ReD is red and it should be able to accept that.

サインインしてコメントする。

その他の回答 (1 件)

Sean de Wolski
Sean de Wolski 2016 年 9 月 19 日
You could use a containers.Map to use non-MATLAB variable names if you want:
mapper = containers.Map('enumclass.A/B','A')
mapper('enumclass.A/B')
  3 件のコメント
Sean de Wolski
Sean de Wolski 2016 年 9 月 20 日
編集済み: Sean de Wolski 2016 年 9 月 20 日
Hi Phillip,
What I was suggesting won't work the way you have it above. For best looks, what you're doing is probably best. I was thinking more like a factory function to generate the enumerations given any key. disp can be overloaded to make it look right. This is probably not a good idea, but it is possible.
e = genEnum('Hello World')
e =
Hello World
Function
function enumObj = genEnum(key)
mapper = containers.Map({'enumclass.A/B','Hello World'},{'A','B'});
enum = mapper(key);
enumObj = EnumClass.(enum);
end
And
classdef EnumClass
enumeration
A
B
end
methods
function disp(obj)
mapper = containers.Map({'A','B'},{'enumclass.A/B','Hello World'});
label = mapper(char(obj));
disp(label)
end
end
end
Sean de Wolski
Sean de Wolski 2016 年 9 月 20 日
Why do you want to do this? What's the bigger picture?

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeSchedule Model Components についてさらに検索

製品

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by