【问题标题】:Function to Return a Replaceable Record in Modelica在 Modelica 中返回可替换记录的函数
【发布时间】:2017-05-18 03:36:34
【问题描述】:

我想定义一个函数,它在给定输入整数索引(0、1 或 2)的情况下返回可替换记录(MyRecord0、MyRecord1 或 MyRecord2)。

请注意,这只是一个简单的演示示例案例,实际上可能会有更多记录,每个记录都包含附加参数。

示例记录的定义如下所示:

  record MyRecord0
    parameter Integer myIndex = 0;
    parameter Real myValue = 0;
  end MyRecord0;

  record MyRecord1
    extends MyRecord0(
      myIndex = 1,
      myValue = 1);
  end MyRecord1;

  record MyRecord2
    extends MyRecord0(
      myIndex = 2,
      myValue = 2);
  end MyRecord2;

我已经能够使用如下所示的 getRecord 函数从函数中成功返回适当的记录,但我需要在函数中为每个记录类型显式声明一个对象。

function getRecord
  input Integer index "record index";
  replaceable output MyRecord0 myRecord;

  // Explicit declaration of instances for each possible record type
  MyRecord0 record0;
  MyRecord1 record1;
  MyRecord2 record2;

algorithm 
  if index == 1 then
    myRecord := record1;
  else
    if index == 2 then
      myRecord := record2;
    else
      myRecord := record0;
    end if;
  end if;   
end getRecord;

任何人都可以提出一种替代语法来消除在函数中声明每种可能记录类型的实例的需要吗?例如,我尝试了如下所示的变体,但找不到可以正确编译的令人满意的方法。

function getRecord_Generic
  input Integer index "record index";
  replaceable output MyRecord0 myRecord;

  redeclare MyRecord1 myRecord if index == 1; else (redeclare MyRecord2 myRecord if index == 2 else redeclare MyRecord0 myRecord);
end getRecord_Generic;

或者

function getRecord_Generic2
  input Integer index "record index";
  replaceable output MyRecord0 myRecord;

algorithm 
  if index == 1 then
    redeclare MyRecord1 myRecord;
  else
    if index ==2 then
      redeclare MyRecord2 myRecord;
    else
      // default case
      redecalre MyRecord0 myRecord;
    end if;
  end if;      
end getRecord_Generic2;

感谢任何提示或建议!

【问题讨论】:

    标签: modelica dymola openmodelica


    【解决方案1】:

    假设这个例子很简单,你可以这样做:

      function getRecord2
      input Integer index "record index";
      output MyRecord0 myRecord;
    
      algorithm 
        if index==1 then
          myRecord := MyRecord1();
      else
        if index == 2 then
          myRecord := MyRecord2();
        else
          myRecord := MyRecord0();
        end if;
      end if;   
    end getRecord2;
    

    (仅使用 Dymola 测试。)

    如果某些不同的记录包含额外的字段,则没有好的解决方案。

    【讨论】:

    • 汉斯,我是否正确理解 () 创建记录的实例?
    • 是的,MyRecord0() 创建记录的一个实例(通过调用自动生成的记录构造函数)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-14
    • 2012-11-29
    • 1970-01-01
    • 1970-01-01
    • 2021-02-19
    • 1970-01-01
    相关资源
    最近更新 更多