コメントと地域

# コメント

プロジェクトでコメントを使用することは、デザインの選択についての説明を残す便利な方法であり、コードを維持または追加するときに、あなた (または他の誰か) の生活を楽にすることを目的としています。

コードにコメントを追加するには、2 つの方法があります。

# 一行コメント

// の後に配置されたテキスト コメントとして扱われます。

public class Program
{
    // This is the entry point of my program.
    public static void Main()
    {
        // Prints a message to the console. - This is a comment!
        System.Console.WriteLine("Hello, World!"); 

        // System.Console.WriteLine("Hello, World again!"); // You can even comment out code.
        System.Console.ReadLine();
    }
}

# 複数行または区切りコメント

/* の間の任意のテキスト そして */ コメントとして扱われます。

public class Program
{
    public static void Main()
    {
        /*
            This is a multi line comment
            it will be ignored by the compiler.
        */
        System.Console.WriteLine("Hello, World!");

        // It's also possible to make an inline comment with /* */
        // although it's rarely used in practice
        System.Console.WriteLine(/* Inline comment */ "Hello, World!");
  
        System.Console.ReadLine();
    }
}

# 地域

領域は、コードの可読性と編成に役立つ折りたたみ可能なコード ブロックです。

注: StyleCop のルール SA1124 DoNotUseRegions は、リージョンの使用を推奨しません。 C# にはリージョンを時代遅れにする部分クラスやその他の機能が含まれているため、これらは通常、コードの編成が適切でないことを示しています。

リージョンは次のように使用できます:

class Program
{
    #region Application entry point
    static void Main(string[] args)
    {
        PrintHelloWorld();
        System.Console.ReadLine();
    }
    #endregion

    #region My method
    private static void PrintHelloWorld()
    {
        System.Console.WriteLine("Hello, World!");
    }
    #endregion
}

上記のコードを IDE で表示すると、+ 記号と - 記号を使用してコードを折りたたんだり展開したりできます。

拡大

崩壊

# ドキュメント コメント

XML ドキュメント コメントを使用して、ツールで簡単に処理できる API ドキュメントを提供できます。

/// <summary>
/// A helper class for validating method arguments.
/// </summary>
public static class Precondition
{
    /// <summary>
    ///     Throws an <see cref="ArgumentOutOfRangeException"/> with the parameter
    ///     name set to <c>paramName</c> if <c>value</c> does not satisfy the 
    ///     <c>predicate</c> specified.
    /// </summary>
    /// <typeparam name="T">
    ///     The type of the argument checked
    /// </typeparam>
    /// <param name="value">
    ///     The argument to be checked
    /// </param>
    /// <param name="predicate">
    ///     The predicate the value is required to satisfy
    /// </param>
    /// <param name="paramName">
    ///     The parameter name to be passed to the
    ///     <see cref="ArgumentOutOfRangeException"/>.
    /// </param>
    /// <returns>The value specified</returns>
    public static T Satisfies<T>(T value, Func<T, bool> predicate, string paramName)
    {
        if (!predicate(value))
            throw new ArgumentOutOfRangeException(paramName);

        return value;
    }
}

ドキュメントは IntelliSense によって即座に取得されます: