Csharp/C Sharp/LINQ/var — различия между версиями
Admin (обсуждение | вклад) м (1 версия) |
|
(нет различий)
|
Версия 18:31, 26 мая 2010
Содержание
An Anonymous Type Assigned to a Variable Declared with the var Keyword
<source lang="csharp">
using System; public class MainClass {
public static void Main() { var unnamedTypeVar = new { firstArg = 1, secondArg = "Joe" }; Console.WriteLine(unnamedTypeVar.firstArg + ". " + unnamedTypeVar.secondArg); }
}
</source>
An Example of Collection Initialization
<source lang="csharp">
using System.Collections.Generic; using System; public class MainClass {
public static void Main() { List<string> presidents = new List<string> { "AAAA", "BBBBBB", "CCCCCCCC" }; foreach (string president in presidents) { Console.WriteLine(president); } }
}
</source>
Anonymous Types
<source lang="csharp"> using System; using System.Collections.Generic; using System.Diagnostics; class MainClass{
static void DisplayProcesses(Func<Process, Boolean> match) { var processes = new List<Object>(); foreach (var process in Process.GetProcesses()) { if (match(process)) { processes.Add(new { process.Id, Name = process.ProcessName, Memory = process.WorkingSet64 }); } } } static void Main(string[] args) { DisplayProcesses(process => process.WorkingSet64 >= 20 * 1024 * 1024); }
}
</source>
Instantiating and Initializing an Anonymous Type Using Object Initialization
<source lang="csharp">
using System; public class MainClass {
public static void Main() { var address = new { address = "First Street", city = "Vancouver", state = "GA", postalCode = "99999" }; Console.WriteLine("address = {0} : city = {1} : state = {2} : zip = {3}", address.address, address.city, address.state, address.postalCode); Console.WriteLine("{0}", address.GetType().ToString()); }
}
</source>
Using var
<source lang="csharp"> using System; using System.Collections.Generic; using System.Diagnostics; class MyPC {
public Int32 Id { get; set; } public Int64 Memory { get; set; } public String Name { get; set; }
} class LanguageFeatures {
static void Main(string[] args) { var processes = new List<MyPC>(); foreach (var process in Process.GetProcesses()) { var data = new MyPC(); data.Id = process.Id; data.Name = process.ProcessName; data.Memory = process.WorkingSet64; processes.Add(data); } Console.Write(processes); }
}
</source>