eEhdsa

New things to .Net4.0 -Lazy<T> - Tuple

1. Tuple

我记得F#中也有类似的数据结构


  Tuple tuple = new Tuple("item1", "item2", 20);
  //Tuple tuple = Tuple.Create("item1", "item2", 20);
  var date = Tuple.Create("item1", "item2", 20);
  Console.WriteLine(tuple.Item1);
  Console.WriteLine(tuple.Item2);
  Console.WriteLine(tuple.Item3);

当然还可以有更多的item, public static Tuple> Create(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6, T7 item7, T8 item8); 其中item8又是一个Tuple, 所以可以无限扩张, 当然T的类型也是


2. Lazy<T>

他的出现解决了大对象加载问题,但是是否有实际意义....我见过不少朋友都自己实现过~而且并不是很复杂, 不过既然封装了当然也就有了它的价值


假象大对象:


[Serializable]
class INeedLazy
{
    public INeedLazy(string name, string age)
    {
        this.Name = name;
        this.Age = age;
    }
    public string Name { get; private set; }
    public string Age { get; private set; }
    public void Test()
    {
        Console.WriteLine("{0} is {1} years old, he is lazy!", Name, Age);
    }
}

lazy加载此对象

    Lazy lazyObj = new Lazy(() =>
    {
    return new INeedLazy("Ryan", "2");
    });
    Console.WriteLine(lazyObj.IsValueCreated);    //false
    lazyObj.Value.Test();
    Console.WriteLine(lazyObj.IsValueCreated);    //true
    Console.WriteLine(lazyObj.Value.Name);

或者lazy加载一个string玩玩

    var lazyString = new Lazy(() =>
    {
        // Here you can do some complex processing
        // and then return a value.
        Console.Write("Inside lazy loader");
        return "Lazy loading!";
    });
    Console.Write("Is value created: ");
    Console.WriteLine(lazyString.IsValueCreated);
    Console.Write("Value: ");
    Console.WriteLine(lazyString.Value);
    Console.Write("Value again: ");
    Console.WriteLine(lazyString.Value);
    Console.Write("Is value created: ");
    Console.WriteLine(lazyString.IsValueCreated);

posted on 2010-02-21 18:12  eEhdsa  阅读(280)  评论(0编辑  收藏  举报

导航