Csharp/C Sharp/LINQ/var

Материал из .Net Framework эксперт
Перейти к: навигация, поиск

An Anonymous Type Assigned to a Variable Declared with the var Keyword

 

using System;
public class MainClass {
    public static void Main() {
        var unnamedTypeVar = new { firstArg = 1, secondArg = "Joe" };
        Console.WriteLine(unnamedTypeVar.firstArg + ". " + unnamedTypeVar.secondArg);
    }
}


An Example of Collection Initialization

 

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);
        }
    }
}


Anonymous Types

 
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);
    }
}


Instantiating and Initializing an Anonymous Type Using Object Initialization

 

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());
    }
}


Using var

 
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);
    }
}