批处理函数获取通过引用传递的变量值

问题描述 投票:0回答:1

在下面的脚本中,我通过引用 myDosFunc 传递 var1,以便它可以更改值。 如何在函数中获取引用变量的值,而不必在两次中传递变量?

set "var1=Hello world"
Echo var1 before: %var1%
call:myDosFunc var1 "%var1%"
Echo var1 after : %var1%
goto :eof

:myDosFunc    -- passing a variable by reference, and changing value
echo   Notice that a variable passed by reference does NOT echo the value, and it echos the variable name instead.
echo   Arg1 variable name = '%~1' and Arg2 value = '%~2'
set "%~1=Good bye world!!!"
goto :eof

我尝试了以下变体,但没有一个能够获得该值。

set "var1=Hello world"
Echo var1 before: %var1%
call:myDosFunc var1
Echo var1 after : %var1%
goto :eof

:myDosFunc    -- passing a variable by reference, and changing value
set "VarValue=%~1"
set "VarVal=%~1%"
echo   Arg1 variable name = '%~1' and to get value, tried this '%%%VarValue%%%' and this '%%VarValue%%' and this '%VarValue%' and this '%%%VarVal%%%' and this '%%VarVal%%' and this '%VarVal%'
set "%~1=Good bye world!"
goto :eof
function batch-file pass-by-reference pass-by-value
1个回答
0
投票

这能解决您的问题吗?

@ECHO OFF
SETLOCAL
set "var1=Hello world"
Echo var1 before: %var1%
call:myDosFunc var1 
Echo var1 after : %var1%
goto :eof

:myDosFunc    -- passing a variable by reference, and changing value
echo   Notice that a variable passed by reference does NOT echo the value, and it echos the variable name instead.

CALL SET "arg2=%%%~1%%"
echo %arg2%
echo   Arg1 variable name = '%~1' and Arg2 value = '%~2'
set "%~1=Good bye world!!!"
goto :eof
最新问题
© www.soinside.com 2019 - 2025. All rights reserved.