標籤:des style blog http color 使用 os io
在我們即將進入ASP.NET開發大門的時候。我們需要先學習一些C#的特有文法。而且對於傳統的webform的開發,我們介紹的這些C#特有文法並不是每個人都熟悉的.本節將介紹一個MVC優良程式員所需要的C#語言特性。
一:c#的基本特性
1.1使用自動實作屬性
c#屬性特性讓你暴露一個類的資料片段,這些資料以及如何設定和接收資料採取了一種松耦合的方式。就是說並不是直接和我們類中的欄位相關聯,而是通過一個對外的介面。我們首先看一下下面的這個叫做 "product" 類 類裡面我們只有一個欄位
using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;namespace 河南雲和資料{ public class Product { private string name; public string Name { get { return name; } set { name = value; } } }}
名稱為"Name"的屬性。get代碼塊(成為getter)中的語句在讀取該屬性值時執行,而set代碼塊(成為 setter)中的語句則對這個屬性賦值時執行(特殊變數value表示要賦予的值)。屬性是由其他類來使用的,就好像它是一個欄位一樣,總而言之。在上述類中,name是欄位。而Name是屬性。
using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;using 河南雲和資料;namespace CW{ class Program { static void Main(string[] args) { Product MyProduct = new Product(); MyProduct.Name = "河南雲和資料Rocky Ren"; string procductname = MyProduct.Name; Console.WriteLine("Product name is {0}",procductname); Console.ReadKey(); } }}通過屬性賦值取值
你可以看出,屬性值的讀取和設定,就像對一個規則的欄位進行讀取操作一樣,使用屬性就要比使用欄位好很多,因為你可以修改get和set塊中的語句,而不需要修改依賴於這個屬性的整個類。但是,當一個類中有很多屬性時,事情就變得枯燥了,所有的getter和setter都要做同樣的事情--填充欄位。於是我們又要做一些冗長的事情。
using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;namespace 河南雲和資料{ public class Product { private int id; public int Id { get { return id; } set { id = value; } } private string name; public string Name { get { return name; } set { name = value; } } private string deacription; public string Deacription { get { return deacription; } set { deacription = value; } } private decimal price; public decimal Price { get { return price; } set { price = value; } } }}
這裡需要說明一點的是我們可以在欄位中(ctrl+r+e)快速封裝這些欄位。
我們希望屬性具有靈活性,但此刻又不需要自訂的getter和setter,解決方案是一種自動實作屬性,也成為”自動屬性“他不需要getter和setter
using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;namespace 河南雲和資料{ public class Product { public int Id { set; get; } public string Name { set; get; } public string Description { set; get; } public decimal Price { set; get; } public string Category { set; get; } }}
在使用自動屬性的時候,有兩個關鍵點要注意。第一是不定義getter和setter的體,第二是不定義由該屬性返回的字型。這兩者都由C#編譯器在這個類被建立時自動完成.使用自動屬性與使用規則沒什麼不同,形成便於代碼閱讀的代碼,並且仍然保持了屬性的靈活性,如果需要改變一個屬性實現的方式,還可以返回規則屬性的格式。
using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;namespace 河南雲和資料{ public class Product { private int id; public int Id { set; get; } private string name; public string Name { set; get; } private string description; public string Description { set; get; } private string price; public decimal Price { set; get; } public string Category { set; get; } }}
使用對象和集合初始化器