Прочитать на английском

Поделиться через


CodeCommentStatement Конструкторы

Определение

Инициализирует новый экземпляр класса CodeCommentStatement.

Перегрузки

CodeCommentStatement()

Инициализирует новый экземпляр класса CodeCommentStatement.

CodeCommentStatement(CodeComment)

Инициализирует новый экземпляр класса CodeCommentStatement, используя указанный комментарий.

CodeCommentStatement(String)

Инициализирует новый экземпляр класса CodeCommentStatement, используя указанный текст в качестве содержимого.

CodeCommentStatement(String, Boolean)

Инициализирует новый экземпляр класса CodeCommentStatement, используя указанный текст и флаг комментария документации.

CodeCommentStatement()

Исходный код:
CodeCommentStatement.cs
Исходный код:
CodeCommentStatement.cs
Исходный код:
CodeCommentStatement.cs

Инициализирует новый экземпляр класса CodeCommentStatement.

public CodeCommentStatement ();

Применяется к

.NET Framework 4.8.1 и другие версии
Продукт Версии
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
Windows Desktop 3.0, 3.1, 5, 6, 7, 8, 9

CodeCommentStatement(CodeComment)

Исходный код:
CodeCommentStatement.cs
Исходный код:
CodeCommentStatement.cs
Исходный код:
CodeCommentStatement.cs

Инициализирует новый экземпляр класса CodeCommentStatement, используя указанный комментарий.

public CodeCommentStatement (System.CodeDom.CodeComment comment);

Параметры

comment
CodeComment

CodeComment, указывающий комментарий.

Применяется к

.NET Framework 4.8.1 и другие версии
Продукт Версии
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
Windows Desktop 3.0, 3.1, 5, 6, 7, 8, 9

CodeCommentStatement(String)

Исходный код:
CodeCommentStatement.cs
Исходный код:
CodeCommentStatement.cs
Исходный код:
CodeCommentStatement.cs

Инициализирует новый экземпляр класса CodeCommentStatement, используя указанный текст в качестве содержимого.

public CodeCommentStatement (string text);

Параметры

text
String

Содержимое комментария.

Применяется к

.NET Framework 4.8.1 и другие версии
Продукт Версии
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
Windows Desktop 3.0, 3.1, 5, 6, 7, 8, 9

CodeCommentStatement(String, Boolean)

Исходный код:
CodeCommentStatement.cs
Исходный код:
CodeCommentStatement.cs
Исходный код:
CodeCommentStatement.cs

Инициализирует новый экземпляр класса CodeCommentStatement, используя указанный текст и флаг комментария документации.

public CodeCommentStatement (string text, bool docComment);

Параметры

text
String

Содержимое комментария.

docComment
Boolean

Значение true, если комментарий является комментарием документации; в противном случае — false.

Примеры

В следующем примере кода показано использование конструктора CodeCommentStatement(String, Boolean) для создания оператора комментария, который будет использоваться в качестве поля комментария XML. Этот пример является частью более крупного примера ниже.

// Declare a new code entry point method.
CodeEntryPointMethod start = new CodeEntryPointMethod();
start.Comments.Add(new CodeCommentStatement("<summary>", true));
start.Comments.Add(new CodeCommentStatement(
    "Main method for HelloWorld application.", true));
start.Comments.Add(new CodeCommentStatement(
    @"<para>Add a new paragraph to the description.</para>", true));
start.Comments.Add(new CodeCommentStatement("</summary>", true));

В следующем примере кода показано создание простого консольного приложения Hello World и создание XML-файла документации для скомпилированного приложения.

using System;
using System.CodeDom;
using System.CodeDom.Compiler;
using System.IO;
using System.Text.RegularExpressions;

namespace BasicCodeDomApp
{
    class Program
    {
        static string providerName = "cs";
        static string sourceFileName = "test.cs";
        static void Main(string[] args)
        {
            CodeDomProvider provider = CodeDomProvider.CreateProvider(providerName);

            LogMessage("Building CodeDOM graph...");

            CodeCompileUnit cu = new CodeCompileUnit();

            cu = BuildHelloWorldGraph();

            StreamWriter sourceFile = new StreamWriter(sourceFileName);
            provider.GenerateCodeFromCompileUnit(cu, sourceFile, null);
            sourceFile.Close();

            CompilerParameters opt = new CompilerParameters(new string[]{
                                      "System.dll" });
            opt.GenerateExecutable = true;
            opt.OutputAssembly = "HelloWorld.exe";
            opt.TreatWarningsAsErrors = true;
            opt.IncludeDebugInformation = true;
            opt.GenerateInMemory = true;
            opt.CompilerOptions = "/doc:HelloWorldDoc.xml";

            CompilerResults results;

            LogMessage("Compiling with " + providerName);
            results = provider.CompileAssemblyFromFile(opt, sourceFileName);

            OutputResults(results);
            if (results.NativeCompilerReturnValue != 0)
            {
                LogMessage("");
                LogMessage("Compilation failed.");
            }
            else
            {
                LogMessage("");
                LogMessage("Demo completed successfully.");
            }
            File.Delete(sourceFileName);
        }

        // Build a Hello World program graph using System.CodeDom types.
        public static CodeCompileUnit BuildHelloWorldGraph()
        {
            // Create a new CodeCompileUnit to contain
            // the program graph.
            CodeCompileUnit compileUnit = new CodeCompileUnit();

            // Declare a new namespace called Samples.
            CodeNamespace samples = new CodeNamespace("Samples");
            // Add the new namespace to the compile unit.
            compileUnit.Namespaces.Add(samples);

            // Add the new namespace import for the System namespace.
            samples.Imports.Add(new CodeNamespaceImport("System"));

            // Declare a new type called Class1.
            CodeTypeDeclaration class1 = new CodeTypeDeclaration("Class1");

            class1.Comments.Add(new CodeCommentStatement("<summary>", true));
            class1.Comments.Add(new CodeCommentStatement(
                "Create a Hello World application.", true));
            class1.Comments.Add(new CodeCommentStatement("</summary>", true));
            class1.Comments.Add(new CodeCommentStatement(
                @"<seealso cref=" + '"' + "Class1.Main" + '"' + "/>", true));

            // Add the new type to the namespace type collection.
            samples.Types.Add(class1);

            // Declare a new code entry point method.
            CodeEntryPointMethod start = new CodeEntryPointMethod();
            start.Comments.Add(new CodeCommentStatement("<summary>", true));
            start.Comments.Add(new CodeCommentStatement(
                "Main method for HelloWorld application.", true));
            start.Comments.Add(new CodeCommentStatement(
                @"<para>Add a new paragraph to the description.</para>", true));
            start.Comments.Add(new CodeCommentStatement("</summary>", true));

            // Create a type reference for the System.Console class.
            CodeTypeReferenceExpression csSystemConsoleType =
                new CodeTypeReferenceExpression("System.Console");

            // Build a Console.WriteLine statement.
            CodeMethodInvokeExpression cs1 = new CodeMethodInvokeExpression(
                csSystemConsoleType, "WriteLine",
                new CodePrimitiveExpression("Hello World!"));

            // Add the WriteLine call to the statement collection.
            start.Statements.Add(cs1);

            // Build another Console.WriteLine statement.
            CodeMethodInvokeExpression cs2 = new CodeMethodInvokeExpression(
                csSystemConsoleType, "WriteLine", new CodePrimitiveExpression(
                "Press the ENTER key to continue."));

            // Add the WriteLine call to the statement collection.
            start.Statements.Add(cs2);

            // Build a call to System.Console.ReadLine.
            CodeMethodInvokeExpression csReadLine =
                new CodeMethodInvokeExpression(csSystemConsoleType, "ReadLine");

            // Add the ReadLine statement.
            start.Statements.Add(csReadLine);

            // Add the code entry point method to
            // the Members collection of the type.
            class1.Members.Add(start);

            return compileUnit;
        }
        static void LogMessage(string text)
        {
            Console.WriteLine(text);
        }

        static void OutputResults(CompilerResults results)
        {
            LogMessage("NativeCompilerReturnValue=" +
                results.NativeCompilerReturnValue.ToString());
            foreach (string s in results.Output)
            {
                LogMessage(s);
            }
        }
    }
}

Комментарии

docComment Если параметр имеет значение true, CodeCommentStatement то является комментарием документации, а комментарий структурирован с помощью символов тройного разделителя. Например, в C# комментарий имеет значение "///", а в Visual Basic " .''' Комментарии к документации используются для идентификации поля комментария XML, например типа или сводки элементов, определяемых элементом <summary> .

Применяется к

.NET Framework 4.8.1 и другие версии
Продукт Версии
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
Windows Desktop 3.0, 3.1, 5, 6, 7, 8, 9