Implicitly typed local variables in Anonymous types

摘要:Implicitly typed local variables in Anonymous types

今天看到Implicitly typed local variables,測試了一下,直覺上設計了這玩意不知道要幹嘛? Orz
但是繼續看下去後,才發覺它的好玩之處...
在匿名型別上,可以透過巢狀的方式設計,或是透過一些基本型別或是強型別的物件來作為屬性(property)。
 

DataSet1TableAdapters.EmployeeTableAdapter em = new DataSet1TableAdapters.EmployeeTableAdapter();

DataTable dt = new DataTable();
dt = em.GetData();
var mytest = new { Test1 = "123", Test2 = 456, Test3 = 12.34 };
var person = new { Name = "Lolota ", Sex = "Male", Age = 99, MyProfile=dt, my=mytest};

label1.Text = person.MyProfile.Rows[0].ItemArray[1].ToString();



 

還有可以拿來處理查詢(LINQ):


 

private static void QueryNames(char firstLetter)
{
    // Create the query. var is required because
    // the query produces a sequence of anonymous types.
    var studentQuery =
        from student in students
        where student.FirstName[0] == firstLetter
        select new { student.FirstName, student.LastName };

    // Execute the query.
    foreach (var student in studentQuery)
    {
        Console.WriteLine("First = {0}, Last = {1}", student.FirstName, student.LastName);
    }
}




 

參考:


 

1.

Implicitly Typed Local Variables
 

2.

How to: Use Implicitly Typed Local Variables and Arrays in a Query Expression

 

 

如果您有微軟技術開發的問題,可以到MSDN Forum發問。

如果您有微軟IT管理的問題,可以到TechNet Forum發問喔。