2012-07-12 146 views
5

我有一个枚举:字符串枚举

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 

和我有一个字符串:

currentCommand = 'PositionMode'; 

我希望能够返回:

Commands.PositionMode 

有没有更好的解决方案比

methods(Static) 
    function obj = str2Command(string) 
     obj = eval(['Commands.' string]); 
    end 
end 

回答

5

与结构一样,可以将dynamic field names与对象一起使用。

随着

currentCommand = PositionMode 

通话

Commands.(currentCommand) 

评估为

Commands.PositionMode 

,从而解决了一个优雅和方便的方式你的问题。