【问题标题】:Weird MATLAB behavior when having containers.Map as a class property将 container.Map 作为类属性时的奇怪 MATLAB 行为
【发布时间】:2013-10-09 13:37:08
【问题描述】:

我创建自己的类如下:

classdef testClass < handle
    properties
        value;
        map = containers.Map('KeyType','double','ValueType','any');
    end
end

我的目标是为testClass 的每个对象维护自己的地图。然而,事实证明整个类只有一个映射对象:testClass 的所有对象都访问同一个containers.Map。例如,如果我创建两个对象如下

a = testClass;
b = testClass;

a.value = 'a';
b.value = 'b';

a.map(1) = 123;
b.map(2) = 321;

最终ab 的映射包含两个键值对:

>> a
a = 
  testClass handle

    Properties:
      value: 'a'
        map: [2x1 containers.Map]

>> b
b = 
  testClass handle

    Properties:
      value: 'b'
        map: [2x1 containers.Map]
    Methods, Events, Superclasses

(key,value) 对 (1,123) 和 (2,321) 都出现在 a.mapb.map

>> a.map.keys
ans = 
    [1]    [2]
>> a.map.values
ans = 
    [123]    [321]

>> b.map.keys
ans = 
    [1]    [2]
>> b.map.values
ans = 
    [123]    [321]

这是一个错误吗?如何为每个类对象保持独立的containers.Map

【问题讨论】:

    标签: matlab properties map containers matlab-class


    【解决方案1】:

    问题不在于testClasshandle,而在于properties 块中指定的初始值在您认为的情况下未被评估。 MATLAB 仅在加载类时计算一次类属性的默认值,然后将该值赋予类的每个新实例。

    您可以通过查看 testClass 的元类来了解这一点。例如:

    c = testClass;
    c.map(1) = 42;
    hc = ?testClass;
    hc.PropertyList(2).DefaultValue.keys % returns [1]
    hc.PropertyList(2).DefaultValue.values % returns [42]
    

    如果您希望每个实例具有不同的映射,则必须在构造函数中显式构建映射。 (是的,我去过那里,做过)。

    【讨论】:

      猜你喜欢
      • 2017-04-10
      • 1970-01-01
      • 2012-01-17
      • 1970-01-01
      • 2023-04-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多