隐式转换运算符和等于运算符 [英] Implicit cast operator and the equality operator

查看:158
本文介绍了隐式转换运算符和等于运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有一个简单的对象,它支持隐式转换为System.String

Say I have a simple object which supports implicit casting to System.String

public sealed class CompanyCode
{
    public CompanyCode(String value)
    {
        // Regex validation on value format
        _value = value;
    }

    private readonly String _value;

    public override String ToString()
    {
        return _value;
    }

    static public implicit operator String(CompanyCode code)
    {
        if(code == null)
            return null;

        return code.ToString();
    }
}

现在让我在程序的其他部分我进行说

Now lets say in another part of my program I perform a comparison with a string:

var companyCode = { some company code object }

if (companyCode == "MSFTUKCAMBS")
    // do something...

什么是编译器与 == 运营商在做什么?是它隐含铸造企业编码为字符串,并运行 System.String == 的实施?难道使用 System.Object的== 的实施?或将编译器只是抱怨我? (我没有一个编译器检查现在这个右)。

What is the compiler doing with the == operator? Is it implicitly casting companyCode to a string and running the System.String == implementation? Is it using the System.Object == implementation? Or will the compiler just complain at me? (I don't have a compiler to check this right now).

据我可以看到我有几个其他的选择。

As far as I can see I have a couple of other options.


  • 实施的 = =(字符串x)运营商的企业编码。

  • 实施 IEquatable<弦乐方式>对企业编码接口

  • Implement an ==(String x) operator on CompanyCode.
  • Implement the IEquatable<String> interface on CompanyCode.

是否有任何(或两者)这些选项最好?

Would any (or both) of these options be preferable?

推荐答案

我个人建议不要使用运算符重载中的这些情况下的。这是一种混淆找上了代码,了解正在发生的事情。

I personally would suggest do not use operator overloading, in these cases. It's kind of confusing looking on the code, to understand what is going on.

这是一个更好的,海事组织,有一些功能是esplicitly的清单的比较操作,或者像乔恩表明,使用属性。

It's a much better, imo, having some function that esplicitly manifests comparison operation, or, like Jon suggests, use a property.

在短期讲清楚你的代码,你会得到什么比较读卡器。

In short make it clear for the reader of your code what you're gonna to compare.

这篇关于隐式转换运算符和等于运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆