考虑以下Matlab(2009a)类:
classdef BigDeal < handle
properties
hugeness = magic(2000);
end
methods
function self = BigDeal()
end
end
end
classdef BigProxy < handle
properties(Dependent)
hugeness
end
properties(Access = private)
bigDeal
end
methods
function self = BigProxy(bigDeal)
self.bigDeal = bigDeal;
end
function value = get.hugeness(self)
value = self.bigDeal.hugeness;
end
end
end
现在考虑以下用途:
设定:
>> b = BigDeal
b =
BigDeal handle
Properties:
hugeness: [10x10 double]
Methods, Events, Superclasses
OneLayer:
>> pb = BigProxy(b)
pb =
BigProxy handle
Properties:
hugeness: [10x10 double]
Methods, Events, Superclasses
TwoLayers:
>> ppb = BigProxy(pb)
ppb =
BigProxy handle with no properties.
Methods, Events, Superclasses
问题:为什么我的双层代理无法在单层可以看到hugeness
?可以计算相关属性 - 但由于某种原因这只会导致一层深度吗?
更新:请参阅下面的答案以获取解决方法。
答案 0 :(得分:4)
这里的问题有两方面:
BigProxy
对象构造函数用于接受具有(非依赖)hugeness
属性(如BigDeal
对象)的输入对象,{{{1}然后,对象可以访问以计算其自己的依赖BigProxy
属性的值。
在创建hugeness
时,您正在将BigProxy
对象传递给BigProxy
构造函数,并且您显然无法从另一个依赖属性计算依赖属性。例如,这是我尝试访问ppb
时抛出的错误:
ppb.hugeness
换句话说,外部??? In class 'BigProxy', the get method for Dependent property 'hugeness'
attempts to access the stored property value. Dependent properties don't
store a value and can't be accessed from their get method.
对象尝试通过访问内部BigProxy
对象的存储值hugeness
来计算其从属hugeness
属性的值,但是没有存储值,因为它是dependent property。
我认为对于这种情况的修复将是BigProxy
构造函数检查其输入参数的类型以确保它是BigProxy
对象,否则抛出错误。 / p>
答案 1 :(得分:4)
Gnovice为“为什么”这个问题提供了一个很好的答案,因此我授予他荣耀的绿色检查。但是,对于那些想要解决问题的人,你可以这样做:
classdef BigDeal < handle
properties
hugeness = magic(10000);
end
methods
function self = BigDeal()
end
end
end
classdef BigProxy < handle
properties(Dependent)
hugeness
end
properties(Access = private)
bigDeal
end
methods
function self = BigProxy(bigDeal)
self.bigDeal = bigDeal;
end
function value = get.hugeness(self)
value = self.getHugeness;
end
end
methods(Access = private)
function value = getHugeness(self)
if isa(self.bigDeal,'BigProxy')
value = self.bigDeal.getHugeness;
else
value = self.bigDeal.hugeness;
end
end
end
end
允许您执行以下操作
>> b = BigDeal;
>> pb = BigProxy(b);
>> ppb = BigProxy(pb);
{b
,pb
,ppb
}中的每一个都具有相同的公共方法和属性。唯一的缺点是我不得不(不必要地恕我直言)用一个新的私人吸气器弄乱BigProxy。