How to determine if an object is a built-in class?
18 次查看(过去 30 天)
显示 更早的评论
How can I determine if an object is a built-in class?
Not only doubles, structs, strings and all those base data types but also stuff like figures, dynamic systems (tf & ss objects)
2 个评论
Steven Lord
2024-4-26
Why? How would you handle those types of data differently than instances of classes defined by non-MathWorks code?
回答(1 个)
Steven Lord
2024-4-26
Okay. You could achieve your stated goal without actually having to ask "Is this an instance of my class or an instance of some other class or other data type?" If you had a method named struct for your class, or if you defined a non-Static method with some other name that accepted just one input, then the input would be an instance of your class. In the case of struct the method would be a converter method, while if it were some other name that returned a struct it would be just an ordinary instance method.
Or if you do need to ask if the object is an instance of one of the classes you created, you don't need to ask the broad question "Is this an instance of a type MathWorks provided?" You could ask a more targeted question, asking if the variable isa instance of one of your classes.
2 个评论
Steven Lord
2024-4-26
I was trying to find a universal way to avoid specifying classes that I want to convert so that it can be applied to any custom tool anybody will write in the future.
So you want to write a function that can accept any array and turn it into a struct? That's a very tall order.
Instead what I would focus on would be overloading struct for your classes. That way you can convert only the pieces of the object that users need to know about (leaving out any internal implementation details.) You could probably delegate some of that work to the built-in struct function and prune out any internal properties that shouldn't be included in the struct.
c = onCleanup(@() disp('bye')) % object in MATLAB without a struct overload
which -all struct(c)
s1 = struct(c) % Call the built-in function; note the warning
s2 = builtin('struct', c) % Would call the built-in even if there's an overload
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Data Type Conversion 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!