ASP.NET C# Coding Conventions


  1. 說明
    1. 命名慣例
      1. Class Library
      2. Project*
    2. 檔案的命名
    3. 類別的命名
    4. 變數的命名
    5. 習慣的詞彙
    6. ASP.NET MVC
  2. 參考資料
  3. 相關連結

筆記 ASP.NET 開發使用 C# 的語法慣例。

logo

說明

命名慣例

Class Library

{組織} . {大類別 / 應用範圍} . {小類別 / 專案名稱}

Microsoft.AspNetCore.Mvc
System.Web.Mvc

Project*

{專案名稱} . {子專案 / 類別 / 應用}

Project.Models
Project.Controllers
Project.Filters
Project.Business

檔案的命名

{
  "View" : "MVC 的 View 與其 Action 有相同的名稱,例如 Index",
  "PartialView" : "使用 _Sidebar.cshtml 表示",
  "Layout" : "使用 _Layout.cshtml 表示",
  "ViewModel" : "使用 ProductViewModel.cs 表示",
}

類別的命名

類別名稱使用 Pascal Case

專用類別的後綴 (suffix)

{
  "Base" : "基底類別 Concrete / Abstract 提供其他的類別繼承",
  "Factory" : "工類模式類別,用於將物件建構的演算法做集合",
  "Collection" : "物件集合類別",
  "Help" : "綜整輔助方法工具",
  "Controller" : "MVC 中 Controller Class 的慣用後綴",
  "Attribute" : "MVC 中繼承 FilterAttribute 實作客製化 Filter 慣用的後綴",
  "Builder" : "",
}

變數的命名

{
  "Field" : "_filed",
  "Static Private Field" : "s_privateField",
  "Property" : "Property",
  "Const" : "CONST",
  "Parameter" : "parameter"
}
public class ClassName
{
    private int _field;
    const double PI = 3.14159;
    private static int s_privateField;
    public int Property { get; set; }


    public ClassName(int parameter)
    {
        _field = parameter;
        s_privateField += 1;
    }

    public double Count
    {
        get { return _field * PI * s_privateField; }
    }
}

習慣的詞彙

{
  "Get" : "從 Database 取得資料",
  "Search" : "對 Collection 或 Database 的資料進行搜尋",
  "Find" : "從 Collection 取得單筆資料",
  "Fetch" : "從遠端 API、WebSrvice 取得資料",
  "Load" : "從本機取得資料 (filesystem)",
  "Populate" : "對物件填充資料,尤其指將 ViewModel 的資料進行填充",
  "Update" : "對 Database 的資料進行更動",
  "Modify" : "對 Collection 的資料進行更動",
  "Insert" : "將資料加入 Database",
  "Create" : "建立物件或者建立 Collection",
  "Generate" : "產生靜態資料 / Fake Data",
  "Delete" : "從 Database 將資料刪除",
  "Remove" : "從 Collection 將資料 / 物件刪除",
  "Convert" : "代碼轉文字/編碼之間的轉換",
}

ASP.NET MVC

參考資料

伊果的沒人看筆記本 - C#: 程式碼風格備忘

C# Coding Style

C# 編碼慣例

相關連結

ASP.NET MVC 從無到有打造一個應用系統

Visual Studio 入門教學