问题
Given the following two classes
classdef EnumClass
enumeration
enumVal1
enumVal2
end
end
classdef EnumDisplay
properties
enumValue = EnumClass.enumVal1
numberValue = 1
end
end
When displaying an EnumClass
, the value is displayed:
>> E = EnumClass.enumVal1
E =
enumVal1
but when displaying EnumDisplay
in the command window, the enumeration value is suppressed, and only the array size and class are displayed.
>> C = EnumDisplay()
C =
EnumDisplay with properties:
enumValue: [1x1 EnumClass]
numberValue: 1
What is the easiest way to have the enumeration value displayed in the class property list. I.e. is there an easy and general way to have the class displayed as follows:
>> C = EnumDisplay()
C =
EnumDisplay with properties:
enumValue: enumVal1
numberValue: 1
I suspect that this has something to do with inheriting from the matlab.mixin.CustomDisplay
class somewhere, but I want this to be as general as possible, to limit the amount of coding i need to do for each enumeration class, and/or each class that has an enumeration value in a property.
Partial Solution
I was able to figure out a partial solution to this problem, but it is not quite satisfactory.
classdef EnumDisplay < matlab.mixin.CustomDisplay
properties
enumValue = EnumClass.enumVal1
numberValue = 1
end
methods (Access = protected)
function groups = getPropertyGroups(This)
groups = getPropertyGroups@matlab.mixin.CustomDisplay(This);
groups.PropertyList.enumValue = char(This.enumValue);
end
end
end
Now the display looks like:
>> C = EnumDisplay()
C =
EnumDisplay with properties:
enumValue: 'enumVal1'
numberValue: 1
This is almost there, but not quite. I don't want the enumerated value to be in quotations.
回答1:
Okay, well... this isn't the most elegant approach -- certainly not as elegant as using matlab.mixin.CustomDisplay
-- but one possibility is to try to replicate that functionality yourself, in a way that gives you more control. Here is what I hacked together on the ferry...
classdef EnumDisplay
properties
enumValue = EnumClass.enumVal1
numberValue = 1
end
methods
function disp(This)
cl = class(This) ;
fprintf(' <a href="matlab:helpPopup %s">%s</a> with properties: \n\n',cl,cl) ;
prop = properties(This) ;
len = max(cellfun(@length,prop)) ;
for ii = 1:numel(prop)
if isnumeric(This.(prop{ii}))
fmt = '%g' ;
else
fmt = '%s' ;
end
filler = char(repmat(32,1,4+len-length(prop{ii}))) ;
fprintf('%s%s: ',filler,prop{ii}) ;
fprintf(sprintf('%s \n',fmt),char(This.(prop{ii}))) ;
end
end
end
end
Result:
>> C = EnumDisplay()
C =
EnumDisplay with properties:
enumValue: enumVal1
numberValue: 1
Only catch is that this may not be fully generic because I may not have appropriately covered all of the possible formats fmt
. But if you are really desperate, maybe something like this will work.
来源:https://stackoverflow.com/questions/22152029/how-can-i-display-enumeration-value-in-matlab-object