필터 지우기
필터 지우기

How do I check if a property exists for an empty object?

조회 수: 17 (최근 30일)
Captain Karnage
Captain Karnage 2023년 10월 18일
답변: Captain Karnage 2023년 10월 18일
I have a function that gets passed an object named exObj . The intent is this object can be one of a set of custom class objects that I have created. If the passed object has a property or method (sometimes I can't assign the property and have to use a static method instead) that has a specific name, there is an additional set of commands that are executed. So, I start that block of code with
if ( isprop(exObj, "flagged" ) || ismethod(exObj, "flagged") )
The problem is, the object passed COULD be an empty version of the object. In that case, as described in the help pages here: https://www.mathworks.com/help/matlab/ref/isprop.html isprop returns an empty logical array and I get the error:
Operands to the logical AND (&&) and OR (||) operators must be convertible to logical scalar values. Use the ANY or ALL functions to reduce operands to logical scalar values.
Interestingly, ismethod does not give the same error. I still want to execute the code block if that property exists - so I can't just add if ~isempty(exObj) before this statement. So, how can I check that this property exists on an empty object?
  댓글 수: 1
Les Beckham
Les Beckham 2023년 10월 18일
I'm not an OOP expert by any means, but don't you know which classes have that property and which don't? Couldn't you check class(exObj) instead of checking for the presence of a certain property?

댓글을 달려면 로그인하십시오.

답변 (1개)

Captain Karnage
Captain Karnage 2023년 10월 18일
After typing it out and pondering for just a little bit, I figured it out. Would still be nice if isprop worked, but this statement works:
ismember( "flagged", properties(exObj) )

카테고리

Help CenterFile Exchange에서 Construct and Work with Object Arrays에 대해 자세히 알아보기

태그

제품


릴리스

R2023a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by