How can i implicitly convert my class to another type?

后端 未结 3 622
自闭症患者
自闭症患者 2021-01-19 05:42

For example implicitly

MyClass myClass = new MyClass();
int i = myClass;
相关标签:
3条回答
  • 2021-01-19 05:57
    class MyClass 
    {
       public static implicit operator int(MyClass myClass) 
       {
          // code to convert from MyClass to int
       }
    }
    

    Take a look there : implicit

    0 讨论(0)
  • 2021-01-19 05:58

    This MSDN entry covers what you want exactly, should do the trick.

    0 讨论(0)
  • 2021-01-19 06:07

    You need to define this in the MyClass file.

    public static implicit operator int(MyClass instance) 
    {
        if (instance == null) 
        {
            return -1;
        }
        return instance._underlyingValue;
    }
    
    0 讨论(0)
提交回复
热议问题