1. 程式人生 > >C#部分語法總結

C#部分語法總結

mar rst comment 方式 啟動應用 != 不存在 如果 名稱

1. Frst和FirstOrDefault

1. Fist

如果查詢的數據不存在, 則System.InvalidOperationException異常

2. FirstOrdefault

如果查詢的數據不存在, 則返回 null

2. => lamba 表達式

3. Array.IndexOf

搜索 Array 對象的指定元素並返回該元素的索引。 此函數是靜態的,可在不創建對象實例的情況下調用。

var indexVar = Array.indexOf(array, item, start);

術語

定義

array

要搜索的數組。

item

要在數組中查找的對象。

startIndex

(可選)指定在數組中搜索的起始元素的索引號。

4. using 三中使用方式

來自:http://www.cnblogs.com/fashui/archive/2011/09/29/2195061.html

1.using指令 using + 命名空間名字,這樣可以在程序中直接用命令空間中的類型,而不必指定類型的詳細命名空間,類似於Java的import,這個功能也是最常用的,幾乎每個cs的程序都會用到。

例如:using System; 一般都會出現在*.cs中。

2.using別名。using + 別名 = 包括詳細命名空間信息的具體的類型。
這種做法有個好處就是當同一個cs引用了兩個不同的命名空間,但兩個命名空間都包括了一個相同名字的類型的時候。當需要用到這個類型的時候,就每個地方都要用詳細命名空間的辦法來區分這些相同名字的類型。而用別名的方法會更簡潔,用到哪個類就給哪個類做別名聲明就可以了。註意:並不是說兩個名字重復,給其中一個用了別名,另外一個就不需要用別名了,如果兩個都要使用,則兩個都需要用using來定義別名的。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 using System; using aClass = NameSpace1.MyClass; using bClass = NameSpace2.MyClass; namespace NameSpace1 { public class MyClass { public override string ToString() { return "You are in NameSpace1.MyClass"; } } } namespace NameSpace2 { class
MyClass { public override string ToString() { return "You are in NameSpace2.MyClass"; } } } namespace testUsing { using NameSpace1; using NameSpace2; /// <summary> /// Class1 的摘要說明。 /// </summary> class Class1 { /// <summary> /// 應用程序的主入口點。 /// </summary> [STAThread] static void Main(string[] args) { // // TODO: 在此處添加代碼以啟動應用程序 // aClass my1 = new aClass(); Console.WriteLine(my1); bClass my2 = new bClass(); Console.WriteLine(my2); Console.WriteLine("Press any key"); Console.Read(); } } }

3.using語句,定義一個範圍,在範圍結束時處理對象。
場景:
當在某個代碼段中使用了類的實例,而希望無論因為什麽原因,只要離開了這個代碼段就自動調用這個類實例的Dispose。
要達到這樣的目的,用try...catch來捕捉異常也是可以的,但用using也很方便。

1 2 3 4 using (Class1 cls1 = new Class1(), cls2 = new Class1()) { // the code using cls1, cls2 } // call the Dispose on cls1 and cls2

5. 數組的操作

Array.Sort(nums/*數組名稱*/);

Array.Reverse(nums/*數組名稱*/);

6. IndexOf

        public static void UseIndexOf()
        {
            string str = "hello cat. hi boatlet. How are you cat? Fine, Thanks!";
                                             //搜索字符串,初始位置
            int index = str.IndexOf("cat", 0);
            int i = 1;
            if(index != -1)
            {
                Console.WriteLine("cat 第{0}次出現位置為{1}", i, index);
                while(index != -1)
                {
                    index = str.IndexOf("cat", index + 1);
                    i++;
                    if(index == -1)
                    {
                        break;
                    }
                    Console.WriteLine("cat 第{0}次出現位置為{1}", i, index);
                }
            }

  

C#部分語法總結