C#:IComparable 实现私有
我是 C# 新手,所以这可能是一个真正的转储问题:我在我的类中实现了 IComparable,并想用 NUnit 对其进行测试。但 CompareTo-Method 被标记为私有,因此无法从测试中访问。
这是什么原因?我该如何解决这个问题?
IComparable:
public class PersonHistoryItem : DateEntity,IComparable
{
...
int IComparable.CompareTo(object obj)
{
PersonHistoryItem phi = (PersonHistoryItem)obj;
return this.StartDate.CompareTo(phi.StartDate);
}
}
测试:
[TestMethod] public void TestPersonHistoryItem() { DateTime startDate = new DateTime(2001, 2, 2); DateTime endDate = new DateTime(2010, 2, 2); PersonHistoryItem phi1 = new PersonHistoryItem(startDate,endDate);
PersonHistoryItem phi2 = new PersonHistoryItem(startDate, endDate); Assert.IsTrue(phi1.CompareTo(phi2)==0); }
<代码>
I'm new to C# so this might be a really dump question: I implemented IComparable in my class and want to test it with NUnit. But the CompareTo-Method is marked as private and thus not accessible from the test.
What's the reason for this and how can I fix this?
The IComparable:
public class PersonHistoryItem : DateEntity,IComparable
{
...
int IComparable.CompareTo(object obj)
{
PersonHistoryItem phi = (PersonHistoryItem)obj;
return this.StartDate.CompareTo(phi.StartDate);
}
}
The test:
[TestMethod]
public void TestPersonHistoryItem() {
DateTime startDate = new DateTime(2001, 2, 2);
DateTime endDate = new DateTime(2010, 2, 2);
PersonHistoryItem phi1 = new PersonHistoryItem(startDate,endDate);
PersonHistoryItem phi2 = new PersonHistoryItem(startDate, endDate);
Assert.IsTrue(phi1.CompareTo(phi2)==0);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
它们不是私有的,它们只是显式实现。将变量声明为
IComparable
应该可以解决问题:They are not private, they are just explicitly implemented. Declaring your variables as
IComparable
should solve the problem:我认为最简单的方法是使用隐式接口实现:
I think the easiest way would be to use implicit interface implementation:
您的方法使用显式接口实现。这意味着除非完成强制转换,否则接口方法不会显示在您的类上。
执行以下操作:
((IComparable)phi1).CompareTo(phi2)
Your approach uses explicit interface implementation. That means that the interface methods will not show up on your class unless a cast is done.
Do this:
((IComparable)phi1).CompareTo(phi2)
这里的主要问题是您显式实现了 CompareTo 方法,该方法仅允许您在将对象用作 IComparable 对象时使用它。
要纠正此问题,请将可见性指定为 public 并非“显式”实现 CompareTo 方法:
The main problem here is that you explicitly implements the CompareTo method, which only allows you to use it when you use your object as a IComparable object.
To correct the problem, specify the visibility as public and implement the CompareTo method not "explicitly" :
在 C# 中,接口不定义访问器,因此您可以将
CompareTo
方法公开,并将显式接口实现从: 更改为:
In C# an interface does not define accessors, so you can make your
CompareTo
method public and change the explicit interface implementation from:To: