Predavatelj: Luke Hoban, Program Manager, Microsoft
Auto-implemented properties
Namesto
public Class Point {
private int x;
private int y;
public int X { get { return x; } set { x = value; } }
public int Y { get { return y; } set { y = value; } }
}
sedaj lahko pišemo
public Class Point {
public int X { get; set; }
public int Y { get; set; }
}
Object initializers
var r = new Rectangle {
P1 = new Point { X = 0, Y = 1 },
P2 = new Point { X = 2, Y = 3 }
};
Collection initializers
var contacts = new List<Contact> {
new Contact {
Name = "Chris Smith",
PhoneNumbers = { "206-555-0101", "425-882-8080" }
},
new Contact {
Name = "Bob Harris",
PhoneNumbers = { "650-555-0199" }
}
};
Local variables type inference
// namesto
Dictionary<int, SomeType> myCol = new Dictionary<int, SomeType>();
// sedaj lahko napišemo
var myCol = new Dictionary<int, SomeType>();
Query expressions
from c in customers
group c by c.Country into g
select new { Country = g.Key, CustCount = g.Count() }
Anonymous types
var p1 = new { Name = "Lawnmower", Price = 495.00 };
var p2 = new { Name = "Shovel", Price = 26.95 };
p1 = p2;
Lambda expressions
x => x + 1 // Implicitly typed, expression body
x => { return x + 1; } // Implicitly typed, statement body
(int x) => x + 1 // Explicitly typed, expression body
(int x) => { return x + 1; } // Explicitly typed, statement body
(x, y) => x * y // Multiple parameters
Extension Methods
Omogočajo razširitev že obstoječih tipov z dodatnimi metodami. Spodaj je primer razreda z dvema takima metodama:
namespace Acme.Utilities
{
public static class Extensions
{
public static int ToInt32(this string s) {
return Int32.Parse(s);
}
public static T[] Slice<T>(this T[] source, int index, int count) {
if (index < 0 || count < 0 || source.Length – index < count)
throw new ArgumentException();
T[] result = new T[count];
Array.Copy(source, index, result, 0, count);
return result;
}
}
}
Expression Trees
Omogočajo, da so lambda izrazi predstavljeni kot podatki in ne kot koda.
Func<int,int> f = x => x + 1; // Code
Expression<Func<int,int>> e = x => x + 1; // Data
Partial Methods
Implicitly-Typed Arrays