使用动态名称调用多行宏?

Calling a multi-line macro by using a dynamic name?

我回来是为了另一个问题,这次是关于宏的。

我想使用 !..! 调用多行宏(如果可能)为了使用动态宏名称,如以下对单行宏的调用:

setlocal disabledelayedexpansion
:: Simple single-line macros for testing purpose.
set "_testA=echo A" & set "_testB=echo B"

setlocal enabledelayedexpansion
:: Choose macro _testA or _testB.
set /p char="Type A or B:"

:: Execute the chosen macro.
!_test%char%!
endlocal

endlocal

例如,

 setlocal disabledelayedexpansion
:: Line feed character.
(set CHR10=^
%=Do not remove this line, or you will be turned into a frog=%
)
 
:: End of line in a macro code.
set ^"\nmac=^^^%CHR10%%CHR10%^%CHR10%%CHR10%^^"

:: Simple multi-line macro for testing purpose, it could be replace with one receiving parameters obviously.
set _test=(echo A%\nmac%
echo B%\nmac%
echo C)

setlocal enabledelayedexpansion
:: Works as expected, displays A then B then C.
%_test%

:: Doesn't work... as expected also, displays `(echo Is Not Recognized as an Internal or External Command, Operable Program or Batch File.`
!_test!
endlocal

endlocal

问题似乎出在使用 with !..! 时 CHR10 的定义问题! (显然,使用 %_test% 有效)。

有解决办法吗?一个解决方案可以帮助我重构一些代码。

预先感谢您的回答。

解决方法很简单,执行 batch macro 总是需要百分比扩展。 显然你不能为百分比扩展使变量名动态化,但你可以使内容动态化。

@echo off
(set ^"$\n=^^^
%= Do not remove this line=%
)

set macro1=(echo #1 Line1 %$\n%
echo #1 Line2)

set macro2=(echo #2 Line1 %$\n%
echo #2 Line2)

setlocal EnableDelayedExpansion
%macro1%
%macro2%
set /p "macroNum=Select 1 or 2: "

set "macroName=macro%macroNum%"

REM *** Copy the content of the 'dynamic macro' to indirectMacro
set "indirectMacro=!%macroName%!"
%indirectMacro%

顺便说一句。您对 \nmac 的定义和使用是多余的,因为单个 linefeed (带有单个插入符号)在批处理宏中就足够了,当它们被括在括号中时。