Can I 'initialize' a handle object in such a way that isvalid(object) would return false?
6 ビュー (過去 30 日間)
古いコメントを表示
I'm trying to initialize a variable (MyHandle) that I want to be a handle pointing to some object but which can't currently be assigned to said object. I have code that needs to behave differently depending on if MyHandle is assigned or not yet and I haven't found a good way to test if MyHandle has been assigned to a valid object or not.
The function 'isvalid' seems like the right choice to test this, however, isvalid throws the error "Incorrect number or types of inputs or outputs for function isvalid." when run on MyHandle in its unassigned state. I've tried different ways to initialize it like "handle([])" and "[]", but they all return that same error.
I've found some bandaid solutions like initializing MyHandle to an instance of some arbitrary handle subclass and then deleting that initialized object, or assigning MyHandle to be a value of type double and then using "isnumeric" as my test function instead of "isvalid," but I was wondering if there is a more "correct" way to do it for the sake of best practices.
Below is a sample class that recreates the behavior described above. To restate my question in terms of the class below: Is there an initialization for MyHandle I can use in the properties block that will allow IsHandleAssigned to return false before the first time AssignHandle is run with a valid handle and return true afterwards? OR is there a different function besides isvalid that I should be using in IsHandleAssigned to achieve that behavior?
classdef ExampleClass < handle
properties
MyHandle %Will be a handle pointing to an object of an arbitrary class
% MyHandle = handle([]) < This initialization returns an error
% MyHandle = [] < This initialization returns an error
% MyHandle = 0 < This works if I replace 'isvalid' with 'isnumeric'
% but that seems like poor practice to do since it obfuscates the
% purpose of MyHandle
end
methods
function obj = AssignHandle(obj,handleIn)
%This method assigns the handle of whatever class it happens to
%be to my property.
obj.MyHandle = handleIn;
end
function HandleIsAssigned = IsHandleAssigned(obj)
%This method tests whether or not my handle was assigned. Is
%there a better function than isvalid to use?
HandleIsAssigned = isvalid(obj.MyHandle);
end
end
end
0 件のコメント
採用された回答
Matt J
2024 年 8 月 30 日
編集済み: Matt J
2024 年 8 月 30 日
One way:
classdef ExampleClass < handle
properties
MyHandle
end
methods
function obj = AssignHandle(obj,handleIn)
obj.MyHandle = handleIn;
end
function HandleIsAssigned = IsHandleAssigned(obj)
HandleIsAssigned = isa(obj.MyHandle,'handle') && isvalid(obj.MyHandle);
end
end
end
その他の回答 (0 件)
参考
カテゴリ
Help Center および File Exchange で Data Type Identification についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!