listings \def 问题

listings \def 问题

当我用 xelatex 编译下面的代码时,%\end{lstlisting}有一行是必须的,以防止出现错误。这是什么问题?

\documentclass[a4paper,11pt, onecolumn, openany,]{memoir}
\usepackage[english]{babel} % English please
%\usepackage[final]{microtype} % Less badboxes
\usepackage{fontspec}


\usepackage{listings}
\usepackage{xcolor}


\newfontfamily{\lstcode}[Scale=0.85]{Ubuntu Mono}
\lstdefinestyle{csharp}
{
     language=[Sharp]C,
     frame=shadowbox,
     rulecolor=\color{white!80!black},
     rulesepcolor=\color{white!80!black},
     basicstyle=\lstcode,
     showstringspaces=false,     
     breaklines=true
}

\def\bcsh#1\ncsh
{
    \lstset{style=csharp}
    \begin{lstlisting}[numbers=left]
    #1
    \end{lstlisting}
}

\begin{document}
\bcsh
class Program
{  
    static void Main()
    {
        System.Console.WriteLine("Hello World!");
        System.Console.ReadKey();
    }
}
\ncsh
%\end{lstlisting}

\end{document}

答案1

简短的回答:您不能将lstlisting环境作为参数传递给宏。

您可以定义一个新的环境。

\documentclass[a4paper,11pt, onecolumn, openany,]{memoir}
\usepackage[english]{babel} % English please
%\usepackage[final]{microtype} % Less badboxes
\usepackage{fontspec}


\usepackage{listings}
\usepackage{xcolor}


\newfontfamily{\lstcode}[Scale=0.85]{Ubuntu Mono}
\lstdefinestyle{csharp}
{
     language=[Sharp]C,
     frame=shadowbox,
     rulecolor=\color{white!80!black},
     rulesepcolor=\color{white!80!black},
     basicstyle=\lstcode,
     showstringspaces=false,     
     breaklines=true
}

\lstnewenvironment{bcsh}[1][]
 {\lstset{style=csharp,numbers=left,#1}}
 {}

\begin{document}
\begin{bcsh}
class Program
{  
    static void Main()
    {
        System.Console.WriteLine("Hello World!");
        System.Console.ReadKey();
    }
}
\end{bcsh}

\end{document}

在此处输入图片描述

相关内容