我有一个这样的课程:
public class Article {
private Category? category;
private string content;
public Article(Category? category,string content){
Contract.Ensures(this.category == category); // error
}
}
但在Ensure
方法上会出现此错误:
运营商' =='不能应用于类别'类别的操作数?'和'类别?'
我该如何避免?
答案 0 :(得分:5)
使用此:
this.category.Equals(category)
答案 1 :(得分:5)
如果您希望能够使用它来比较该类型的两个实例(无论是否可为空),则需要重载该类型的==
运算符。
答案 2 :(得分:0)
首先实施 等于 类别类
public struct Category // turned out that Category is a struct
{
public int Field {get; set; } // for demo purpose only
public override bool Equals(Object that)
{
if (that == null)
{
return false;
}
else
{
if (that is Category)
{
// select the fields you want to compare between the 2 objects
return this.Field == (that as Category).Field;
}
return false;
}
}
}
然后在您的代码中,您可以使用等于方法
Contract.Ensures(this.category.Equals(category))