列表 \def 問題

列表 \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}

在此輸入影像描述

相關內容