ASP.NET - 隱含型別、匿名方法、匿名型別

  • 272
  • 0
  • 2018-08-16

隱含型別、匿名方法、匿名型別

隱含型別 var ,滑鼠移到var就可以發覺編譯器以右邊的值判定該變數的類型

var value = "1"

匿名方法(無具名方法):

使用匿名方法 + lambda表示式 & 具名方法的委派 比較差別。

 

// Declare a delegate.
delegate void Printer(string s);

class TestClass
{
    static void Main()
    {
        // Instantiate the delegate type using an anonymous method.
        // Printer p = delegate(string j)
        Printer p = j=>
        {
            System.Console.WriteLine(j);
        };

        // Results from the anonymous delegate call.
        p("The delegate using the anonymous method is called.");

        // The delegate instantiation using a named method "DoWork".
        p = new Printer(TestClass.DoWork);

        // Results from the old style delegate call.
        p("The delegate using the named method is called.");
    }

    // The method associated with the named delegate.
    static void DoWork(string k)
    {
        System.Console.WriteLine(k);
    }
}
/* Output:
    The delegate using the anonymous method is called.
    The delegate using the named method is called.
*/

或是可以在物件初始化時,當作建構子參數傳入

void StartThread()
{
    System.Threading.Thread t1 = new System.Threading.Thread
      (p_message =>
            {
                System.Console.Write(p_message );
                System.Console.WriteLine("World!");
            });
    t1.Start("Hello");

    //Hello
}

匿名型別

匿名類型提供一個便利的方法,將一組唯讀屬性封裝成一個物件,而不需要事先明確定義類型。

var myAnonymous = new {price=100,name="大亨堡"}

Console.writeline(myAnonymous.GetType());

//<>f__AnonymousType0`2[System.Int32,System.String]

 也可以宣告匿名型別的Array

var myAnonymous = new[] {new {price=100,name="大亨堡"}
,new {price=20,name="科學麵"}}

Console.writeline(myAnonymous.GetType());

//<>f__AnonymousType0`2[System.Int32,System.String]

 

 

參考連結一連結二連結三