c# – 平等和分配运算符

我有一个用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#中使用程序集执行相等性检查时,如果(qtr!= null)我收到错误:

无法将类型’object’隐式转换为’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();}

我需要做什么才能使相等运算符正常运行?

解决方法:

当我按原样实现你的代码并将实例比较为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与你的相等运算符一致.

上一篇:C中的“ – >”运算符是什么?


下一篇:是什么 !! (不是)JavaScript中的运算符?