Как мне написать тестовый код для использования универсальной пары C # <TKey, TValue>? - PullRequest
0 голосов
/ 30 апреля 2010

Я читаю "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"

Что я делаю не так?

Спасибо

Scott

Ответы [ 2 ]

2 голосов
/ 30 апреля 2010

Вы должны указать, какие типы вы используете.

Pair<String, String> thePair = new Pair<String, String>(new String("1"), new String("1"));
2 голосов
/ 30 апреля 2010
    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>
...