那些年,我還在學習C# 學習筆記續

來源:互聯網
上載者:User

那些年,我還在學習C#續
那些年學習C#,就是對C#相關的一些知識有一個瞭解,等到要用時才不會找不到方向,比如說擴充方法,開始時怎麼覺得沒有用,後來瞭解到asp.net MVC,它可以用來擴充Html類,比如做一個分頁的方法;所以對一門語言瞭解寬一些是沒有壞處的;C#中還有一些在上文中沒有提到的,如:讀取檔案、網路(socket)編程、序列化等,他們都是非常重要的啊,下面再來看一看吧!
一、讀取檔案
在檔案讀取學習時,一般都會提到位元組流與字元流,前都按位元組讀取,後都按字元讀取;我們通過FileStream、StreamWriter、StreamReader、BinaryWriter、BinaryReader來完成,在System.IO空間中提供了他們的使用,讀取檔案操作不僅再傳統型程式中有用,而且在asp.net web程式中也很有用,通過讀取檔案可以產生靜態網頁,一些不需要互動的頁面,都可以做成靜態頁面,比如新聞。下面來看一下具體是怎麼用他們的吧:
1、 StreamWriter、StreamReader的使用: 複製代碼 代碼如下:/// <summary>
/// Writer通過路徑來得讀取檔案,並寫入資料
/// </summary>
/// <param name="path">路徑</param>
public void FileOpOrCreateWriter(string path)
{
//開啟或建立一個檔案
using (FileStream fs = new FileStream(path, FileMode.OpenOrCreate))
{
//向開啟檔案中寫入資料
using (StreamWriter sw = new StreamWriter(fs, Encoding.UTF8))
{
//寫入資料
sw.WriteLine("my name is whc");
sw.Flush();
}
}
}
/// <summary>
/// Reader讀取檔案
/// </summary>
/// <param name="path">路徑</param>
public void FileOpOrCreateReader(string path)
{
using (FileStream fs = new FileStream(path, FileMode.OpenOrCreate))
{
using (StreamReader sr = new StreamReader(fs, Encoding.UTF8))
{
Console.WriteLine(sr.ReadLine());
}
}
}

2、 BinaryWriter、BinaryReader的使用 複製代碼 代碼如下:/// <summary>
/// Writer二進位的寫入方法
/// </summary>
/// <param name="path"></param>
public void FileOpOrCreateBinaryWriter(string path)
{
using (FileStream fs = new FileStream(path, FileMode.OpenOrCreate))
{
using (BinaryWriter bw = new BinaryWriter(fs, Encoding.UTF8))
{
string myStr = "this is a Good boy 中國!!!";
//得到字串的二制代碼
byte[] bt = new UTF8Encoding().GetBytes(myStr); //UTF8Encoding().GetBytes(myStr);
Console.WriteLine("二進位為:" + bt + ",大小:" + bt.Length);
bw.Write(bt);
bw.Flush();
}
}
}
/// <summary>
/// BinaryReader讀取資料
/// </summary>
/// <param name="path"></param>
public void FileOpOrCreateBinaryReader(string path)
{
using (FileStream fs = new FileStream(path, FileMode.OpenOrCreate))
{
using (BinaryReader br = new BinaryReader(fs, Encoding.UTF8))
{
char[] myStr = new char[1024];
//得到字串的二制代碼
byte[] bt = br.ReadBytes(1024);
//解碼
Decoder d = new UTF8Encoding().GetDecoder();
d.GetChars(bt, 0, bt.Length, myStr, 0);
Console.WriteLine(myStr);
}
}
}

3、 檔案的其它操作 複製代碼 代碼如下:/// <summary>
/// 刪出檔案
/// </summary>
/// <param name="path"></param>
public void DeleteFile(string path)
{
try
{
File.Delete(path);
}
catch (Exception e)
{
Console.WriteLine("It is errors");
}
}
/// <summary>
/// 顯示目錄下的檔案
/// </summary>
/// <param name="path"></param>
public void getDirectorInfo(string path)
{
//得到目錄下的目錄
string[] fileNameList = Directory.GetDirectories(path);
for (int i = 0; i < fileNameList.Length; i++)
{
Console.WriteLine(fileNameList[i]);
FileInfo fi = new FileInfo(fileNameList[i]);
Console.WriteLine(" 檔案名稱:" + fi.FullName);
Console.WriteLine(" 檔案建立的時間:" + fi.CreationTime);
Console.WriteLine(" 最後訪問時間:" + fi.LastAccessTime);
}
}

二、 序列化
在C#中序列化又叫做序列化,是.net平台運行環境支援使用者定義型別的流化機制,其作用是以某種形勢儲存讓對象持久化,或是在網路中傳輸,可以存放在檔案,或是資料庫中,應用程式下次啟動時可以讀取上一次儲存的態狀,以便在不同的就用程式中共用資料,其主要作用如下:
  1、在進程下次啟動時讀取上次儲存的對象的資訊
  2、在不同的AppDomain或進程之間傳遞資料
  3、在分布式應用系統中傳遞資料
 .NET提供了三種方式來序列化一個對象,主要有:
  1、二進位方式,BinaryFormatter,可以使用IFormatter介面來使用它 using System.Runtime.Serialization.Formatters.Binary;
    將對象序列化為二進位,代碼如下:
     複製代碼 代碼如下: /// <summary>
/// 序列化一個對象到記憶體中
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
private byte[] Serializable(SerializableObj obj)
{
IFormatter ifmt = new BinaryFormatter();
using (MemoryStream ms = new MemoryStream())
{
ifmt.Serialize(ms, obj);
return ms.ToArray();
}
}

2、SoapFormatter using System.Runtime.Serialization.Formatters.Soap;IFormatter介面來使用它 沒有時,可添加對應的程式集
   Soap方式是一種簡單對象訪問形式,是一種輕量的、簡單的、基於XML的協議,它被設計成在WEB上交換結構化的和固化的資訊。
   SOAP 可以和現存的許多網際網路協議和格式結合使用,包括超文字傳輸通訊協定 (HTTP)(HTTP),簡易郵件傳輸通訊協定(SMTP),多用途網際郵件擴充協議(MIME)。
   它還支援從訊息系統到遠端程序呼叫(RPC)等大量的應用程式。SOAP使用基於XML的資料結構和超文字傳輸通訊協定 (HTTP)(HTTP)的組合定義了一個標準的方法來使用Internet上各種不同作業環境中的分布式對象。)
代碼如下:
    複製代碼 代碼如下:/// <summary>
/// 還原序列化一個記憶體中的對象
/// </summary>
/// <param name="byteData"></param>
/// <returns></returns>
private SerializableObj DeSerializable(byte[] byteData)
{
IFormatter ifmt = new SoapFormatter();
using (MemoryStream ms = new MemoryStream(byteData))
{
return (SerializableObj)ifmt.Deserialize(ms);
}
}

  3、XML序列化 using System.Xml.Serialization;.XmlSeralizer要求類有個預設的構造器
    複製代碼 代碼如下:XmlSerializer xsl = new XmlSerializer(typeof(SerializableObj));
using (MemoryStream ms = new MemoryStream(byteData))
{
return (SerializableObj)xsl.Deserialize(ms);
}

我們分別可以通過這幾種方式完成需要的序列化
同時,我們在指定類的時候也可以通過特性說明哪些需要序列化,哪些不需要序列化,如下: 複製代碼 代碼如下:[Serializable]//需要序列化
class SerializableObj
{
[NonSerialized] //不需要序列化
public int OrderId;
public string OrderName;
public SerializableObj() { }
public SerializableObj(int OrderId, string OrderName)
{
this.OrderId = OrderId;
this.OrderName = OrderName;
}
public override string ToString()
{
return "OrderId:" + OrderId + "\t\nOrderName:" + OrderName;
}
}

4、自訂序列化
  自訂序列化可以使用ISerializable介面,並且實現GetObjectData()方法,就可以自訂序列化的方式,如下: 複製代碼 代碼如下:class CumstomSerializable:ISerializable
{
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
throw new NotImplementedException();
}
}

三、 Linq的學習
linq是C#3.0的新添加的一個特性,為了使得查詢更容易,同時可以對集合進行操作,使得對資料庫與集合的操作更加簡單,如:Linq to sql、Linq to dataset等,Linq查詢運算式是以"from"開始,以一個"select子句"或是"group by子句"結束.
1、Linq中的關鍵字
·from:指定資料來源以 用來迭代資料來源的變數(範圍變數)
·where:過濾查詢結果
·select:指定查詢結果中的項
·group:通過某一關鍵字,對相關的值進行彙總
·into:儲存彙總中的結果,或串連到一個臨時變數
·orderby:查詢結果按某一關鍵字升序或降序排列
·join:通過一個關鍵字,對兩個資料來源進行串連
·let:建立一個臨時變數,來表示子查詢的結果
2、System.Linq.Enumernable類的方法
·Aggregate():對序列中的每一項應用同一個函數
·Average():返回序列中每一項的平均值
·Count():返回序列的總項數
·Distinct():返回序列中不同的項
·Max():返回序列中的最大值
·Min():返回序列中的最小值
·Select():返回序列中某些項或屬性
·Single():返回序列中的某一個單一值
·Skip():跳過序列中指定數目的項並返回剩下的元素
·Take():返回序列中的指數目的元素
·Where():過濾序列中的元素
·OrderBy():返回傳某一特定欄位升序排序的結果
·OrderByDescending():返回按某一特定欄位降序排序的查詢結果
·ThenBy():返回使用某一額外欄位排序的查詢結果
·ThenByDescending():返回使用霜一額外欄位進行降序排序的查詢結果
·SingleOrDefault():選擇單獨一行或預設的執行個體
·Skip():允許跳過指定數量的記錄
·Take():允許獲得一定數量的記錄
4、 樣本: 複製代碼 代碼如下:List<string> linqList = new List<string>() {
"Demo1","Demo2","Demo3"
};
//lq是一個範圍變數,where是條件,看起來很像SQL語句
IEnumerable<string> results = from lq in linqList where lq.Contains("2") select lq;
foreach (var result in results)
{
System.Console.WriteLine(result.ToString());
}

結果:Demo2
Linq查詢被翻譯時會調用System.Linq.Enumernable類的方法,將Linq語句翻譯成查詢語句與查詢方法:var demo = linqList.Where(m => m.Contains("2")).Select(m => m); 結果同上
總結:
那些年學習C#,主要是對它的一些基礎知識的學習,同時也是在asp.net web開發時更好的使用C#進行編程,此文以回憶那些年學習C#的日子。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.