.net 4.0 学习笔记(2)—— CLR和BCL的更新

更新众多,所以只选择记录一些感兴趣的更新。

一、 异常处理

  在System.Runtime.ExceptionServices命名空间下。

  1. CorruptedStateExceptions

  很多人这样写异常处理:

try
{
    //do something that may fail
    throw new Exception();
}
catch(Exception e)
{
    //handle
}

  这种做法很不好,Exception是异常基类,会隐藏掉所有异常信息。另外,有一些异常通常不会去catch,比如访问权限和非法指令。这些异常会导致严重后果,所以我们最后立即停止程序。在.net 4.0中,堕落异常不会被扑捉到,除非你显式声明在app config。

  LegacyCorruptedStateExceptionsPolicy=true

  这种行为也可以使用标签 [HandleProcessCorruptedStateExceptions]

  2. 新类型

  BigInteger(大整数)

  Lazy<T>

  内存映射文件

    内存映射文件就是把文件映射到内存,这样可以提高速度,并且可以在2个程序共享。

//Create a memory mapped file, write something
using (MemoryMappedFile MemoryMappedFile = MemoryMappedFile.CreateNew("test", 100))
{
MemoryMappedViewStream stream = MemoryMappedFile.CreateViewStream();
using (BinaryWriter writer = new BinaryWriter(stream))
{
writer.Write("hello memory mapped file!");
}
Console.WriteLine("Press any key to close mapped file");
Console.ReadKey();
}

//Read a memory mapped file
using (MemoryMappedFile MemoryMappedFile = MemoryMappedFile.OpenExisting("test"))
{
using (MemoryMappedViewStream Stream = MemoryMappedFile.CreateViewStream())
{
BinaryReader reader = new BinaryReader(Stream);
Console.WriteLine(reader.ReadString());
}
Console.ReadKey();
}

  SotredSet<T>

SortedSet<int> MySortedSet = new SortedSet<int> { 8, 2, 1, 5, 10, 5, 10, 8 };

  ISet<T>接口

  Tuple 元组

 

 

 

Tuple<int, int, int, int, int> MultiplesOfTwo = Tuple.Create(2, 4, 6, 8, 10);
Console.WriteLine(MultiplesOfTwo.Item2);  //output: 4

  System.Numerics.Complex

Complex c1 = new Complex(8, 2);
Complex c2 = new Complex(8, 2);
Complex c3 = c1 + c2;

  Enum.HasFlag()

 

 

[Flags]
public enum CarOptions
{
AirCon = 1,
Turbo = 2,
MP3Player = 4
}
static void Main(string[] args)
{
CarOptions myCar = CarOptions.MP3Player | CarOptions.AirCon | CarOptions.Turbo;
Console.WriteLine("Does car have MP3? {0}", myCar.HasFlag(CarOptions.MP3Player));
Console.ReadKey();
}

  String.IsNullOrWhiteSpace(" ");

  Environment.Is64BitProcess and Environment.Is64BitOperatingSystem

  IObservable<T>

 

Environment.Is64BitProcess and
Environment.Is64BitOperatingSystem

 

 

posted @ 2010-02-24 16:27  primeli  阅读(709)  评论(0编辑  收藏  举报