如何编写测试代码来练习C#泛型对<tkey,tvalue =“”>?</tkey,>

时间:2010-04-30 01:02:10

标签: c# generics collections

我正在阅读Jon Skeet的“C#in Depth”,第一版(这是一本很棒的书)。我在第3.3.3节,第84页,“实现泛型”。泛型总是让我困惑,所以我写了一些代码来练习样本。提供的代码是:

using System; 
using System.Collections.Generic;

public sealed class Pair<TFirst, TSecond> : IEquatable<Pair<TFirst, TSecond>>
{
    private readonly TFirst first; 
    private readonly TSecond second;

    public Pair(TFirst first, TSecond second) 
    {
        this.first = first; 
        this.second = second;
    }


    ...property getters...


    public bool Equals(Pair<TFirst, TSecond> other) 
    {
        if (other == null) 
        {
            return false;
        } 
        return EqualityComparer<TFirst>.Default.Equals(this.First, other.First) &&    
            EqualityComparer<TSecond>.Default.Equals(this.Second, other.Second);
    }

我的代码是:

class MyClass
{
    public static void Main (string[] args)
{
    // Create new pair.
    Pair thePair = new Pair(new String("1"), new String("1"));

    // Compare a new pair to previous pair by generating a second pair.
    if (thePair.Equals(new Pair(new string("1"), new string("1"))))
        System.Console.WriteLine("Equal");
    else
        System.Console.WriteLine("Not equal");
    }
}

编译器抱怨:

“使用泛型类型'ManningListing36.Paie'需要2个类型参数CS0305”

我做错了什么?

谢谢,

斯科特

2 个答案:

答案 0 :(得分:2)

    Pair<string, string> thePair = new Pair<string, string>("1", "1");

    // Compare a new pair to previous pair by generating a second pair.
    if (thePair.Equals(new Pair<string, string>("1", "1")))
        System.Console.WriteLine("Equal");
    else
        System.Console.WriteLine("Not equal");

The type Pair as you use it is Pair<T1, t2>

答案 1 :(得分:2)

您必须指定您正在使用的类型。

Pair<String, String> thePair = new Pair<String, String>(new String("1"), new String("1"));