代码改变世界

C#泛型回顾点滴

2014-11-21 22:52  周信达  阅读(191)  评论(0编辑  收藏  举报

前言

C#的泛型一直是学习者津津乐道的课题了,这确实是一个非常有用的特性,不过在实际使用中,还是有很多需要注意的地方,我们需要通过自己动手实践以及结合理论进行理解,最终总结出自己的编码规范和最佳实践

案例1

internal struct TestStruct : IEquatable<TestStruct>
{
    bool IEquatable<TestStruct>.Equals(TestStruct other)
    {
        return true;
    }
}

internal class TesterClass
{
    // Methods
    public static bool AreEqual<T>(T arg1, T arg2) where T : IEquatable<T>
    {
        return arg1.Equals(arg2);
    }

    public static void Run()
    {
        TestStruct t1 = new TestStruct();
        TestStruct t2 = new TestStruct();
        Debug.Assert(((IEquatable<TestStruct>)t1).Equals(t2));
        Debug.Assert(AreEqual<TestStruct>(t1, t2));
    }
}

案例2

class Program
{
    static void Main(string[] args)
    {
        Print1(1);
        Print2(1);
        Print3(1);

        string a = "ABC";
        string b = "AB";
        string c = b + "C";

        bool genericEquals = IsEquals<string>(a, c);
        bool directEquals = (a == c);

        Console.ReadKey();
    }

    static void Print1<T>(T item)
        where T : struct
    {
        string s = item.ToString();
    }

    static void Print2<T>(T item)
    {
        string s = item.ToString();
    }

    static void Print3(int item)
    {
        string s = item.ToString();
    }

    static bool IsEquals<T>(T t1, T t2)
        where T : class
    {
        return t1 == t2;
    }

}

思考以上代码,在内部是怎样的执行过程?结果如何?为什么?

要点

  • 泛型中的装箱和拆箱
  • 泛型中的逆变与协变

未完待续、、、

参考:

http://stackoverflow.com/questions/5531948/how-does-a-generic-constraint-prevent-boxing-of-a-value-type-with-an-implicitly

http://stackoverflow.com/questions/4403055/boxing-unboxing-and-generics

http://stackoverflow.com/questions/390900/cant-operator-be-applied-to-generic-types-in-c

http://blogs.msdn.com/b/ericlippert/archive/2010/09/30/the-truth-about-value-types.aspx