Static implicit operator

后端 未结 4 1203
孤城傲影
孤城傲影 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:43

    This is a conversion operator. It means that you can write this code:

    XmlBase myBase = new XmlBase();
    XElement myElement = myBase;
    

    And the compiler won't complain! At runtime, the conversion operator will be executed - passing myBase in as the argument, and returning a valid XElement as the result.

    It's a way for you as a developer to tell the compiler:

    "even though these look like two totally unrelated types, there is actually a way to convert from one to the other; just let me handle the logic for how to do it."

提交回复
热议问题