【发布时间】: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