泛型T 如何在扩展方法中使用?

本来想了解一下扩展方法,但是看到文库中的实例明显有问题,特来提问
泛型对象T 如何使用Length 属性?
可以像类中一样加继承于某某类的约束吗?

http://wenku.baidu.com/link?url=Vz-Cjrq24tvblbk0l1I4IPYYfZ82jkGpzGBoNBDhi6qSCJko9hSTcrKGWrunO91TqTgyqB0AMvueHUP1or-mi8ktWMejceDW6Y-OphMnBh7

 public static class testEx
    {
        public static int ToInt32haha(this string str)
        {
            return Int32.Parse(str);
        }
        public static T[] Slice<T>(this T source, int index, int count)
        {
            if (index < 0 || count < 0 || index + count > source.Length)
            {
                throw new ArgumentException();
            }
            T[] result = new T[count];
            Array.Copy(source, index, result, 0, count);
            return result; 
        }
    }
         public static T[] Slice<T>(this IEnumerable<T> source, int index, int count)
        {
            if (index < 0 || count < 0 || index + count > source.Count())
            {
                throw new ArgumentException();
            }
            T[] result = new T[count];
            Array.Copy(source.ToArray(), index, result, 0, count);
            return result;
        }

你对testEx加上泛型约定,testEx: where .....

public static T[] Slice(this T source, int index, int count) where T : IList
{

}

IList有Count,IEnumerable有Count(),都可以代替Length

你用的是VS2005?或者你没有using System.Linq?

你的source应该是集合或者数组,而不是单个的T,我帮你修改了下,你参考下。