2013-07-18 93 views
0

因此,給定一個類,我想有一個屬性誰設置函數返回一些值,以表明它是否成功設置值。來自設置函數的返回值

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 

所以我會有一堆酒吧對象,我想將它們傳遞給富,直到它接受其中之一。我知道我可以在課堂以外做這件事,但我希望所有的數據驗證都在課堂上進行。

我搞砸了試圖讓設置函數返回另一個值,但沒有任何工作。這可能嗎?

如果不是我的解決方法是添加一個屬性,其唯一目的是報告最後一組是否成功,並在每次調用後檢查該屬性。所以如果它不可能有其他人有一個很好的解決方法這個缺少的功能?

編輯:在回答第一個回答

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

在測試這不起作用。我誤解了你的答案嗎?

+0

有你累了設置'Foo'作爲手柄類'classdef美孚 Shai

+0

是的,對setter函數沒有影響 – csleys

回答

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 
+0

我需要能夠以編程方式測試它是否成功。查看問題編輯。 – csleys

+0

@csleys設置屬性後,查詢它並比較get(myobj,'A')== 1'。或者你想通知聽衆? – Oleg

+0

我擴展了我的例子。我想要的是傳遞一個對象到另一個對象,讓它執行數據驗證,並告訴我,如果通過布爾返回或其他東西傳遞的對象是可以接受的。 – csleys