Why can't we define properties on enumerations extending from built-in classes?
2 次查看(过去 30 天)
显示 更早的评论
Trying to understand why we can't subclass something like a uint8 and add a property. Say I want to enumerate data types and conveniently bundle the size of instances of the type in bytes.
In this first case, we specify which uint8 we want each enumeration member to correspond to in parens next to the name, and this works fine:
classdef DataTypeEnumeration < uint8
enumeration
UINT8 (0)
UINT16 (1)
UINT32 (2)
UINT64 (3)
end
end
In totally user-defined classes we use these parens to set properties, like
classdef DataTypeEnumeration
properties
underlying_value
end
enumeration
UINT8 (0)
UINT16 (1)
UINT32 (2)
UINT64 (3)
end
methods
function obj = DataTypeEnumeration(v)
obj.underlying_value = v
end
end
end
but it does not seem there is any way to use this syntax for the built-in type, even if I am not actually trying to define a new property:
classdef DataTypeEnumeration < uint8
properties
some_special_underlying_value_property
end
enumeration
UINT8 (0)
UINT16 (1)
UINT32 (2)
UINT64 (3)
end
methods
function obj = DataTypeEnumeration(v)
obj.some_special_underlying_value_property = uint8(v)
end
end
end
or even just
classdef DataTypeEnumeration < uint8
enumeration
UINT8 (0)
UINT16 (1)
UINT32 (2)
UINT64 (3)
end
methods
function obj = DataTypeEnumeration(v)
obj = uint8(v)
end
end
end
seems like it should work. It kind of feels like the only reason we can't tack on a property to an enumeration of some built-in type is because the interface doesn't support it, which would be sad. What would be the harm in being able to let the parent object be constructed with the first argument and set properties with following arguments, like
classdef DataTypeEnumeration < uint8
properties
bytes
end
enumeration
UINT8 (0, 1)
UINT16 (1, 2)
UINT32 (2, 4)
UINT64 (3, 8)
end
methods
function obj = DataTypeEnumeration(b)
obj.bytes = b
end
end
end
0 个评论
采纳的回答
Matt J
2024-9-28
编辑:Matt J
2024-9-28
I don't know why. I suspect it is for the same reason why builtin indexing and concatenation no longer works when you add properties to a subclass of a builtin class.Much of the functionality of enumerations might depend on builtin cat and indexing.
In any case, you can achieve much the same thing by using Static methods, e.g.,
classdef DataTypeEnumeration < uint8
properties (SetAccess=immutable)
bytes
end
methods (Access=protected)
function obj=DataTypeEnumeration(data, bytes)
obj@uint8(data);
obj.bytes=bytes;
end
end
methods (Static)
function obj = UINT8, obj=DataTypeEnumeration(0,1); end
function obj = UINT16, obj=DataTypeEnumeration(1,2); end
function obj = UINT32, obj=DataTypeEnumeration(2,4); end
function obj = UINT64, obj=DataTypeEnumeration(3,8); end
end
end
0 个评论
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Enumerations 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!