Static implicit operator

后端 未结 4 1195
孤城傲影
孤城傲影 2020-12-07 09:28

I recently found this code:

 public static implicit operator XElement(XmlBase xmlBase)
 {
     return xmlBase.Xml;
 }

What does stati

4条回答
  •  暖寄归人
    2020-12-07 09:54

    Another interesting usage is (which Unity did to check if an object (and therefore an instance of MonoBehavior) is null):

    public static implicit operator bool (CustomClass c)
    {
        return c != null;
    }
    

    Note that the code has to be inside the class (CustomClass in this case). That way you can do something like this:

    void Method ()
    {
        CustomClass c1 = null;
        CustomClass c2 = new CustomClass ();
    
        bool b1 = c1; // is false
        bool b2 = c2; // is true
    
        if (!c1 && c2)
        {
            // Do stuff
        }
    }
    

    Obviously the most notorious use might be using it to convert one of your classes to another of your classes. But using them with basic types is worth a consideration as well... and I see it mentioned quite rarely.

提交回复
热议问题