简体   繁体   English

平等和分配操作员

[英]Equality and Assignment Operators

I have an assembly compiled in VB.NET that contains two operators: 我有一个用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

However, when using the assembly in C# to perform equality checks if (qtr != null) I receive the error: 但是,当在C#中使用程序集执行相等性检查时, if (qtr != null)我收到错误:

Cannot implicitly convert type 'object' to 'bool'

Usage in C# MVC4, Razor: 用于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();}

What do I need to do to make the equality operator behave properly? 我需要做什么才能使相等运算符正常运行?

When I implement your code as-is and compare an instance to null I get a NullReferenceException in your equality operator. 当我按原样实现你的代码并将实例比较为null时,我在你的相等运算符中得到一个NullReferenceException However if I add a null check it works fine: 但是,如果我添加一个空检查它工作正常:

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

I suspect something else is causing the error you're getting. 我怀疑还有其他因素导致你得到的错误。

Most likely you're using the assignment operator ( = ) when you should be using the equality operator ( == ): 最有可能你正在使用赋值运算符( = )时,你应该使用等号( == ):

if (qtr = null)   // wrong  - assigning null to qtr
if (qtr == null)  // correct

In addition, I would recommend overriding Equals and GetHashCode to be consistent with your equality operator. 另外,我建议重写EqualsGetHashCode以与您的相等运算符保持一致。

You can't overload assignment operators, neither in VB or C#. 您不能在VB或C#中重载赋值运算符。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM