4

我有一个在 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();}

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

4

2 回答 2

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

此外,我建议覆盖EqualsGetHashCode与您的相等运算符保持一致。

于 2012-11-13T22:51:46.643 回答
0

在 VB 或 C# 中都不能重载赋值运算符。

http://msdn.microsoft.com/en-us/library/8edha89s.aspx

于 2012-11-13T23:00:50.203 回答