Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String to Enumeration

I have an enumerator:

classdef Commands

    properties
        commandString;
        readonly;
    end
    methods
        function obj = Commands(commandString, readonly)
            obj.commandString = commandString;
            obj.readonly= readonly;
        end
    end
    enumeration
        PositionMode('p', false)
        TravelDistance('s', false)
    end
end

and i have a string:

currentCommand = 'PositionMode';

I want to be able to return:

Commands.PositionMode

Is there any better solution than

methods(Static)
    function obj = str2Command(string)
        obj = eval(['Commands.' string]);
    end
end
like image 768
checkThisOut Avatar asked Jul 12 '12 08:07

checkThisOut


1 Answers

As with structures, you can use dynamic field names with objects.

With

currentCommand = PositionMode

the call

Commands.(currentCommand)

evaluates to

Commands.PositionMode

and thus solves your problem in an elegant and convenient way.

like image 119
Jonas Avatar answered Sep 22 '22 06:09

Jonas