在 \csname 宏上使用 \ifdefined

在 \csname 宏上使用 \ifdefined

我已经多次遇到过这个问题,并且已经用其他方法解决了。但如果知道如何正确解决,就会更简单。

我想\ifdefined在必须用 调用的宏的上下文中使用\csname。也就是说,我想确定\ABC123(aka \csname ABC123\endcsname) 是否已定义。

\documentclass{article}

\begin{document}
\ifdefined\A \verb|\A| is defined as ``\A''\else \verb|\A| is undefined\fi

\def\A{I am defined}

\ifdefined\A \verb|\A| is defined as ``\A''\else \verb|\A| is undefined\fi

\expandafter\ifdefined\csname ABC123\endcsname \verb|\ABC123| is defined\else 
  ABC123 is undefined\fi.  
{\bfseries$\leftarrow$Here I was hoping to detect undefined}

\expandafter\def\csname ABC123\endcsname{abc123}

\expandafter\ifdefined\csname ABC123\endcsname \verb|\ABC123| is defined as
  ``\csname ABC123\endcsname''\else \verb|\ABC123| is undefined\fi

\end{document}

在此处输入图片描述

答案1

使用\ifcsname A\endcsname,这正是您想要的。

对于\expandafter\ifdefined\csname A\endcsname,如果\A未定义,它将等同于\relax。对于 则不会发生这种情况\ifcsname

\documentclass{article}

\begin{document}
\ifdefined\A \verb|\A| is defined as ``\A''\else \verb|\A| is undefined\fi

\def\A{I am defined}

\ifdefined\A \verb|\A| is defined as ``\A''\else \verb|\A| is undefined\fi

\ifcsname ABC123\endcsname \verb|\ABC123| is defined\else
  ABC123 is undefined\fi.
{\bfseries$\leftarrow$Here I was hoping to detect undefined}

\expandafter\def\csname ABC123\endcsname{abc123}

\ifcsname ABC123\endcsname \verb|\ABC123| is defined as
  ``\csname ABC123\endcsname''\else \verb|\ABC123| is undefined\fi

\end{document}

在此处输入图片描述

相关内容