我有一个用VB.NET编译的程序集,它包含两个运算符:
Public Shared Operator =(quarterA As CalendarQuarter, quarterB As CalendarQuarter) As Boolean
Return quarterA.StartDate = quarterB.StartDate AndAlso
quarterA.EndDate = quarterB.EndDate AndAlso
quarterA.Quarter = quarterB.Quarter
End Operator
Public Shared Operator <>(quarterA As CalendarQuarter, quarterB As CalendarQuarter) As Boolean
Return Not (quarterA = quarterB)
End Operator
但是,在C#中使用程序集执行相等性检查时if (qtr != null)
我收到错误:
Cannot implicitly convert type 'object' to 'bool'
用于C#MVC4,Razor:
@{Html.BeginForm();}
<div class="ui-form ui-form-horizontal form-width-narrow">
<div class="title">
Choose a Quarter</div>
<div class="group">
<label><strong>Control</strong></label>
<div class="field">
@Html.DropDownListFor(x => x.Quarter, new SelectList(Model.AvailableQuarters))
<input value="Select" class="ui-button" type="submit" />
</div>
</div>
@if (Model.Quarter != null) {
// Error in the above statement
}
</div>
@{Html.EndForm();}
如何使等式运算符正常运行?
答案 0 :(得分:3)
当我按原样实现你的代码并将一个实例比较为null时,我在你的相等运算符中得到一个NullReferenceException
。但是,如果我添加一个空检查它可以正常工作:
Public Shared Operator =(quarterA As CalendarQuarter, quarterB As CalendarQuarter) As Boolean
If quarterA Is Nothing OrElse quarterB Is Nothing Then Return False
Return quarterA.StartDate = quarterB.StartDate AndAlso
quarterA.EndDate = quarterB.EndDate AndAlso
quarterA.Quarter = quarterB.Quarter
End Operator
我怀疑还有其他因素导致你得到的错误。
当你应该使用等于运算符(=
)时,很可能你正在使用赋值运算符(==
):
if (qtr = null) // wrong - assigning null to qtr
if (qtr == null) // correct
此外,我建议overriding Equals
and GetHashCode
与您的相等运算符保持一致。
答案 1 :(得分:0)
您不能在VB或C#中重载赋值运算符。