How can i implicitly convert my class to another t

2019-02-23 09:16发布

For example implicitly

MyClass myClass = new MyClass();
int i = myClass;

3条回答
Bombasti
2楼-- · 2019-02-23 09:42

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

查看更多
虎瘦雄心在
3楼-- · 2019-02-23 10:02
class MyClass 
{
   public static implicit operator int(MyClass myClass) 
   {
      // code to convert from MyClass to int
   }
}

Take a look there : implicit

查看更多
我命由我不由天
4楼-- · 2019-02-23 10:05

You need to define this in the MyClass file.

public static implicit operator int(MyClass instance) 
{
    if (instance == null) 
    {
        return -1;
    }
    return instance._underlyingValue;
}
查看更多
登录 后发表回答