泛型类不能匹配参数列表

时间:2010-11-01 21:39:25

标签: c# unit-testing class generics

尝试在C#中编写我的第一个泛型类:

public class HighScoreList<ScoreType>
    where ScoreType : System.IComparable<ScoreType>
{
    ...

    public HighScoreList(List<ScoreType> highScoreList)
    {
          ....
    }

    ...
}

我遇到了为它编写单元测试的问题。它不能出于某种原因匹配构造函数的参数列表并给出错误:

错误7“TDGLX.FileManagement.HighScoreList.HighScoreList(System.Collections.Generic.List)”的最佳重载方法匹配包含一些无效参数C:\ Users \ eric \ Documents \ Visual Studio 2010 \ Projects \ TDGLX \ UnitTests \ FileManagmentTest \ HighScoreListTest.cs 183 54 UnitTests

关于这个和其他几个测试:

   HighScoreList<GenericScore> highScoreList =
        new HighScoreList<GenericScore>(new List<GenericScore>()
                {
                    new GenericScore("Person1",400),
                    new GenericScore("Person2",200),
                    new GenericScore("Person3",100)
                });

        HighScoreList<GenericScore> target =
            new HighScoreList<GenericScore>(highScoreList);

这是我在测试中用作模板参数列表参数的类。

[Serializable()]
public class GenericScore : System.IComparable<GenericScore>
{
    public GenericScore(string name,int score)
    {
        Name = name;
        Score = score;
    }

    public string Name { get; set; }
    public int Score { get; set; }

    public int CompareTo(GenericScore other)
    {
        return this.Score.CompareTo(other.Score);
    }
}

我真的无法弄清楚测试有什么问题。有没有什么东西误解了C#generics?

2 个答案:

答案 0 :(得分:6)

    HighScoreList<GenericScore> target =
        new HighScoreList<GenericScore>(highScoreList);

在上面的代码中,您将HighScoreList<GenericScore>传递给HighScoreList<GenericScore>的构造函数,但它需要List<GenericScore>

这不是你想要的吗?

    List<GenericScore> highScoreList = new List<GenericScore>()
            {
                new GenericScore("Person1",400),
                new GenericScore("Person2",200),
                new GenericScore("Person3",100)
            };

    HighScoreList<GenericScore> target =
        new HighScoreList<GenericScore>(highScoreList);

答案 1 :(得分:3)

在第二次调用HighScoreList ctor时,您传递的HighScoreList<GenericScore>实例作为List<GenericStore> ctor参数,但HighScoreList<T>未继承List<T>,因此错误。

作为一种风格,泛型类型名称通常以T开头,因此它将是HighScoreList<TScoreType>,或仅HighScoreList<T>