从set函数返回值

时间:2013-07-18 19:16:22

标签: matlab oop

所以给定一个类我想拥有一个设置函数的属性返回一些值来指示它是否成功设置了值。

classdef Foo
  properties
    bar;
  end
  methods
    function this = set.bar(this, instanceOfBar)
      if instanceOfBar.x < 5 & instanceOfBar < 10
        this.bar = instanceOfBar;
        return something to tell me that this instance of bar matched my criteria
      else
        return some value to tell me that it did not match
      end
    end
  end
end

classdef bar
  properties
    x;
    y;
  end
end

所以我会有一堆bar对象,我想将它们传递给foo,直到它接受其中一个。我知道我可以在课外做这个,但我想在课堂上进行所有数据验证。

我已经搞砸了试图让set函数返回另一个值,但没有任何效果。这可能吗?

如果不是我的解决方法是添加一个属性,其唯一目的是报告最后一组是否成功,并在每次通话后检查。那么,如果不可能有其他人对这个缺失的功能有一个很好的解决方法吗?

编辑:回答第一个答案

if set(myobject, 'A', 1) == 'Good'
  execute code
else
  do something else

在测试中,这不起作用。我误解了你的答案吗?

1 个答案:

答案 0 :(得分:1)

您需要创建hgsetget的子类才能use the get/set interface

classdef foo < hgsetget
    properties
        A
    end
    methods 
        function obj = set.A(obj,val)
        if val == 1
            obj.A = val;
            disp('Good')
        else
            disp('Bad')
        end
        end
    end
end

行动中:

myobj = foo
myobj = 
  foo with properties:
    A: []

set(myobj,'A',1)
Good

get(myobj)
A: 1