代码改变世界

.net 4.0新特性-tuple

2010-06-09 17:02  Clingingboy  阅读(1515)  评论(0编辑  收藏  举报

功能:动态返回数据结构,可当临时数据结构

class Program
{
    static void Main(string[] args)
    {
        //Before
        new People() {Name = "Terry", Age = 24};
        //Now,Create Dynamic struct
        var data = Tuple.Create("Terry", 24);
    }
}
public struct People
{
    public string Name { get; set; }

    public int Age { get; set; }
}
2.比较
var t1 = Tuple.Create(12.3, Double.NaN, 16.4);
var t2 = Tuple.Create(12.3, Double.NaN, 16.4);

以上两个对象参数相同
(1)调用默认的Equals方法
// Call default Equals method.
Console.WriteLine(t1.Equals(t2));

结果输出为True

(2)使用IStructuralEquatable,这个接口为新增,需要一个实现IEqualityComparer对象

IStructuralEquatable equ = t1;
// Call IStructuralEquatable.Equals using default comparer.
Console.WriteLine(equ.Equals(t2, EqualityComparer<object>.Default));

实质上上面调的都是同一个方法,内部还是调用的默认Equals方法比较
看一个内部tuple的Equals实现
bool IStructuralEquatable.Equals(object other, IEqualityComparer comparer)
{
    if (other == null)
    {
        return false;
    }
    Tuple<T1, T2, T3> tuple = other as Tuple<T1, T2, T3>;
    if (tuple == null)
    {
        return false;
    }
    return ((comparer.Equals(this.m_Item1, tuple.m_Item1) && comparer.Equals(this.m_Item2, tuple.m_Item2)) && comparer.Equals(this.m_Item3, tuple.m_Item3));
}

(3)传引用类型,输出为false
var t1 = Tuple.Create(12.3, Double.NaN, new People(){Age = 1});
var t2 = Tuple.Create(12.3, Double.NaN, new People() { Age = 1 });

// Call default Equals method.
Console.WriteLine(t1.Equals(t2));

来看看有几个tuple…好多…如果真有这么多参数,也是应该定义一个类型了
image


参考:http://kb.cnblogs.com/page/47206/