对多种属性使用一套方法MATLAB [英] Use one set method for multiple properties MATLAB
本文介绍了对多种属性使用一套方法MATLAB的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有几个本质上使用相同的 set
方法的属性:
I have several properties that use essentially the same set
method:
classdef MyClass
properties
A
B
end
methods
function mc = MyClass(a,b) % Constructor
mc.A = a;
mc.B = b;
end
function mc = set.A(mc, a) % setter for A
if a > 5
mc.A = a;
else
error('A should be larger than 5');
end
end
function mc = set.B(mc, b) %setter for B
if b > 5
mc.B = b;
else
error('B should be larger than 5');
end
end
end
end
-
是否可以仅对变量
A
和B
使用一个set
函数?(请注意,error
函数使用属性名称作为字符串.)
Is there a way to use only one
set
function for variablesA
andB
? (Please note that theerror
function use the property names as strings.)
是否建议仅使用一个 set
函数?使用一个 set
函数可能有哪些弊端?
Is it suggested to use only one set
function? What are the possible drawbacks of using one set
function?
推荐答案
唯一真正的方法是将通用代码提取到另一个函数,然后从设置器中调用它:
The only real way is to extract the common code to another function, and call it from the setters:
classdef MyClass
properties
A
B
end%public properties
methods
function mc = MyClass(a,b) % Constructor
mc.A = a;
mc.B = b;
end
function mc = set.A(mc, value) % setter for A
mc = mc.commonSetter(value, 'A');
end
function mc = set.B(mc, value) %setter for B
mc = mc.commonSetter(value, 'B');
end
end%public methods
methods(protected = true)
function mc = commonSetter(mc, property, value)
if value <= 5;
error([property ' should be less than 5');
end
mc.(property) = value;
end%commonSetter()
end%protected methods
end%classdef
这篇关于对多种属性使用一套方法MATLAB的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文