C#容易忽略的小知識

一:時間格式話中H和h的區別

DateTime.ToString("yyyy-MM-dd HH:mm:ss");//轉化成24小時

DateTime.ToString("yyyy-MM-dd hh:mm:ss");//轉化成12小時


 二:跳出for foreach 

1:break--跳出for全部(這個循環工作不幹了,繼續其他工作)

2:continue--跳出本次循環,進入下次循環(這次不幹了,下次繼續)

3:return --整個方法、函數都停了(撂挑子,啥不幹了)


 三:關於四捨六入五取餘

c#中的轉int類型遵守的是四捨六入五取餘而不是四捨五入

複製代碼
            var x = 50.5;
            var y = 51.5;
            Console.WriteLine(Math.Round(x, 0));//五舍六入
            Console.WriteLine(Math.Round(x, 0, MidpointRounding.AwayFromZero));//四捨五入
            Console.WriteLine((int)x);
            Console.WriteLine(Convert.ToInt32(x));//四捨六入五取餘
            Console.WriteLine((int)y);
            Console.WriteLine(Convert.ToInt32(y));//四捨六入五取餘
            Console.ReadKey();
複製代碼

  想要使用四捨五入要用math.round(x,0,MidpointRounding.AwayFromZero);


 四:list、數組 相互轉換

list轉數組的時候需要聲明也可以直接toarray();

 


五:註釋的意義:

下面引用一段關於註釋的要求:1):能夠準確反映設計思想和代碼邏輯 2):描述業務含義,使別的程序員能夠迅速瞭解到代碼背後的信息。完全沒有註釋的大段代碼對於閱讀者形同天書,註釋是給自己看的,及時隔很長時間,也能清晰理解當時的思路;註釋也是給繼任者(不是別人是繼任者)看的,使其能夠快速接替自己的工作。


 六:[AuthorizeIgnore]

字面意思就是忽略驗證,實際作用是在進行mvc項目中Attributes驗證的整個流程中如果有那個環節不需要進行驗證則在方法頭上加上該標籤

 [AuthorizeIgnore]
        public ActionResult Regsiter()
        {
            return View();
        }

這樣就不走下圖的方法(寫在admincontrolbase中,爲了驗證)

 /// <summary>
        /// 方法執行前,如果沒有登錄就調整到Passport登錄頁面,沒有權限就拋出信息
        /// </summary>
        /// <param name="filterContext"></param>
        protected override void OnActionExecuting(ActionExecutingContext filterContext)

 七:字符串轉化數組

 var str = Branchid.Split(',');
//方法可配置string int 之間相互轉換
int[] ms = Array.ConvertAll<string, int>(str, s => int.Parse(s));

 


八:mvc中model設置長度驗證
 [MaxLength(16, ErrorMessage = "最大長度16")]
    public string SomeProperty{get;set;}
//這個如果在頁面不起作用的話可以試一試
[StringLength(16, ErrorMessage = "最大長度16")]

 


 

九:lamd 中的order by 
//兩個條件爲並列 order by id,status desc
return iqaccount.OrderByDescending(a => a.ID).OrderByDescending(a=>a.Status).ToPagedList(request.PageIndex, request.PageSize);
//兩個條件有先後順序 select * from  (select * from table order by id desc ) a order by a.status desc
return iqaccount.OrderByDescending(a => a.ID).ThenByDescending(a => a.Status).ToPagedList(request.PageIndex,request.PageSize);