1
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace GenericCount
{
    class Program
    {
        static int Count1<T>(T a) where T : IEnumerable<T>
        {
            return a.Count();
        }

        static void Main(string[] args)
        {
            List<string> mystring = new List<string>()
            {
                "rob","tx"
            };

            int count = Count1<List<string>>(mystring);******
            Console.WriteLine(count.ToString());

        }
    }
}

我必须在上面指示的代码行中进行哪些更改才能使其正常工作。我只是想通过列表或数组来获取计数。

4

4 回答 4

4

你要这个

static int Count1<T>(IEnumerable<T> a)
{
    return a.Count();
}
于 2008-10-02T02:04:54.950 回答
0

您的通用约束是错误的。你不能强制它来实现 IEnumerabl<T>

于 2008-10-02T01:44:32.003 回答
0

你有“where T : IEnumerable<T>”,这不是你想要的。将其更改为例如“IEnumerable<string>”,它将编译。在这种情况下,“T”是 List<string>,它是一个 IEnumerable<string>。

于 2008-10-02T01:44:39.727 回答
0

您的 count 方法需要一种 IEnumerable 类型,然后您已将 T 设置为 List 这意味着该方法将需要 IEnumerable> 这不是您传入的内容。

相反,您应该将参数类型限制为 IEnumerable,并且可以使 T 不受约束。

namespace GenericCount
{
    class Program
    {
        static int Count1<T>(IEnumerable<T> a)
        {
            return a.Count();
        }

        static void Main(string[] args)
        {
            List<string> mystring = new List<string>()
        {
            "rob","tx"
        };

            int count = Count1(mystring);
             Console.WriteLine(count.ToString());

        }
    }
}
于 2008-10-02T02:11:15.357 回答