一、字符串模板技术——StringTemplate
我们可以使用 StringTemplate 来处理一下的问题
1、嵌入式代码自动生成,模板化的程序
2、文本协议输出,根据文本协议,轻松完成复制的输出过程。
模板:常用 (*.st) 为扩展符,这个文件中只含有一个模板,以 $ $ 定义需要替代的变量。
test.st:
void Delay(int del);
// 主函数
void main(void)
{
int $arg1$ = 0;
int $arg2$ = 1;
$! 调用延时 !$
Delay(100);
}
void Delay(int del)
{
int i=1000;
int j=10000;
while(i--);
while(j--);
}
C#中操作:
StringTemplateGroup group = new StringTemplateGroup("g1",AppDomain.CurrentDomain.BaseDirectory);
StringTemplate st = group.GetInstanceOf("test");// 模板名 test.st
st.SetAttribute("arg1", "param1"); // 模板中需替代的变量 arg1
模板组:常用 (*.stg) 为扩展符,这个文件最少含有一个模板,模板组名应和文件名保持一致。以 << >> 定义模板,< > 定义需要替代的变量名。
LDF21.stg:
group LDF21;
Single_description(
file_description,
protocol_version,
language_version,
speed,
Channel_name)
::=
<<
<if(<file_description>)>
LIN_description_file ;
<endif>
<if(<speed>)>
LIN_speed = <speed> "kbps";
<endif>
<if(<protocol_version>)>
LIN_protocol_version = "<protocol_version>" ;
<endif>
<if(<language_version>)>
LIN_language_version = "<language_version>" ;
<endif>
<if(<Channel_name>)>
Channel_name = "<Channel_name>" ;
<endif>
>>
C#操作:
PathGroupLoader loader = new PathGroupLoader(AppDomain.CurrentDomain.BaseDirectory, null);
StringTemplateGroup g = loader.LoadGroup("LDF21");
// 获得模板句柄
StringTemplate st1 = g.GetInstanceOf("speed_description");
StringTemplate st2 = g.GetInstanceOf("protocol_version_description");
StringTemplate st3 = g.GetInstanceOf("language_version_description");
StringTemplate st4 = g.GetInstanceOf("channel_name_description");
// 设置模板属性
st1.SetAttribute("speed", 19.2);
st2.SetAttribute("protocol_version", 2.1);
st3.SetAttribute("language_version", 2.1);
st4.SetAttribute("Channel_name", "DB1");
// 输出数据
OutText.Text = st1.ToString();
OutText.Text += st2.ToString();
OutText.Text += st3.ToString();
OutText.Text += st4.ToString();
通过上面的代码,就可以生成 LDF(LIN总线协议文本)的部分输出了。
5717

被折叠的 条评论
为什么被折叠?



