c# - 通用类无法匹配参数列表

标签 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 单元测试

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

   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# 泛型存在误解?

最佳答案

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

关于c# - 通用类无法匹配参数列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4073285/

相关文章:

python - 使用模拟来修补不存在的属性

unit-testing - 在进行 TDD 时,您如何保持纪律?

php - 在 PHP 中使用命名空间

c# - 我怎么知道表格何时显示?

c# - 如何在 C# 中进行并发 API 调用?

c# - AutoMapper:如何在展平时使用字符串参数 MapFrom

c# - 当我创建一个新类的实例时,我该如何做到这一点,它必须获得一个参数?

java - 如何使用 Google App Engine 插件从 WAR 中排除单元测试?

c++ - 如何在对象中使用 C++ 中的 "this"指针?

python - 尝试调用类方法时出现 NameError 问题