如何编写测试代码来练习 C# 通用 Pair?
我正在阅读 Jon Skeet 的《C# in Depth》第一版(这是一本很棒的书)。我在第 84 页第 3.3.3 节“实现泛型”。泛型总是让我感到困惑,因此我编写了一些代码来练习该示例。提供的代码是:
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”
我做错了什么?
谢谢,
斯科特
I am reading through Jon Skeet's "C# in Depth", first edition (which is a great book). I'm in section 3.3.3, page 84, "Implementing Generics". Generics always confuse me, so I wrote some code to exercise the sample. The code provided is:
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);
}
My code is:
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");
}
}
The compiler complains:
"Using the generic type 'ManningListing36.Paie' requires 2 type argument(s) CS0305"
What am I doing wrong ?
Thanks,
Scott
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您必须指定您正在使用的类型。
You have to specify what types you are using.