码迷,mamicode.com
首页 > Windows程序 > 详细

C#泛型回顾点滴

时间:2014-11-21 23:08:31      阅读:377      评论:0      收藏:0      [点我收藏+]

标签:style   io   ar   os   使用   sp   on   art   bs   

前言

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;
    }

}

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

要点

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

未完待续、、、

C#泛型回顾点滴

标签:style   io   ar   os   使用   sp   on   art   bs   

原文地址:http://www.cnblogs.com/fecktty2013/p/4114401.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!