HA

C# 對一個類進行方法上的擴展 & 為方法添加註釋

C# 對一個類進行方法上的擴展 & 為方法添加註釋

static class StringExtension {
        /// <summary>
        /// 將字符串包裝成數據庫查詢時需要的樣式
        /// 一定程度上防止SQL注入?(我覺得可以達到這個效果)
        /// </summary>
        /// <param name="str">
        /// 需要包裝的字符串
        /// </param>
        /// <returns>包裝後的字符串</returns>
        public static String Quote(this String str) {
            return "'" + str.Replace("'", "''") + "'";
        }
}
//對String類進行擴展,添加一個方法用於組合sql語句
//方法必須在一個靜態類中定義
String str = "tom' or (1=1) --";
Program.log(String.Format("select 1 from user where user = {0} and psd = {1}", str, ""));
Program.log(String.Format("select 1 from user where user = {0} and psd = {1}", str.Quote(), ""));
/*
select 1 from user where user = tom' or (1=1) -- and psd = 
select 1 from user where user = 'tom'' or (1=1) --' and psd = 
*/