如何将字符串转换为枚举?
将枚举转换为字符数组非常简单 - 您只需调用 char
即可。
char(myenum.somevalue)
返回'somevalue'
。
如何再次转换回来?我期待类似 char2enum
的内容,其中
char2enum('somevalue', 'myenum')
返回 myenum.somevalue
。
是否有内置函数,或者我必须创建自己的函数?
To convert an enumeration to be a character array is straightforward – you just call char
.
char(myenum.somevalue)
returns 'somevalue'
.
How do convert back again? I was expecting something like char2enum
where
char2enum('somevalue', 'myenum')
returns myenum.somevalue
.
Is there a builtin function for this or must I create my own?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以使用 MATLAB Dynamic 引用功能通过字符串名称(而不是符号名称)来访问枚举。例如,给定一个类
Weekdays
您可以通过多种方式访问
Friday
类型:如果您有一个包含也有效的类名称的字符串变量:
BTW ,此功能适用于 MATLAB 类方法、属性和事件以及结构体字段。
http://www.mathworks.com/help/matlab /matlab_prog/bsgigzp-1.html#bsgigzp-33
You can use MATLAB Dynamic reference feature to access the enumeration by its name as a string instead of its symbolic name. For example, given a class
Weekdays
You can access the
Friday
type in a couple of ways:If you have a string variable with the name of the class that works too:
BTW, this feature works for MATLAB Class methods, properties, and events, as well as struct fields.
http://www.mathworks.com/help/matlab/matlab_prog/bsgigzp-1.html#bsgigzp-33
从字符创建枚举也相当简单:只需创建枚举:
out = myenum.somevalue
返回类
myenum
和值somevalue
。如果您的字符串位于变量中,请调用
Creating an enum from a character is also fairly straightforward: Just create the enumeration:
out = myenum.somevalue
returns out with class
myenum
and valuesomevalue
.If your string is in a variable, call
我知道这个问题很久以前就已经得到了解答,但我刚刚发现了一个不同的解决方案,在参数块中使用枚举时该解决方案非常简洁。另外,我在官方文档中找不到对此功能的任何引用,因此我想将其发布在这里:
可以使用元素名称作为唯一参数来调用任何枚举的构造函数。例如
,好的,所以我们可以省略这个点。但为什么这很有趣呢?那么,当使用枚举作为函数参数时,参数块允许从字符串/字符自动转换为枚举。
。
I know this question has been answered a long time ago, but I just found out about a different solution which can be pretty neat when using enums in an argument block. Also I couldn't find any reference to this feature in the official documentation so I thought I'd post it here:
The constructor for any enumeration can be called using an element name as sole argument. E.g.
Ok, so we can omit the dot. But why is this interesting? Well, when using enums as a function argument, the argument block allows for automatic conversion from string/char to enumeration.
.