2

事实上MyClass x = 120;,是否可以创建这样一个自定义类?如果是这样,我该怎么做?

4

4 回答 4

5

It's generally considered a bad idea to use implicit operators, as they are, after all, implicit and run behind your back. Debugging code littered with operator overloads is a nightmare. That said, with something like this:

public class Complex
{
    public int Real { get; set; }
    public int Imaginary { get; set; }

    public static implicit operator Complex(int value)
    {
        Complex x = new Complex();
        x.Real = value;
        return x;
    }
}

you could use:

Complex complex = 10;

or you could ever overload the + operator

public static Complex operator +(Complex cmp, int value)
{
  Complex x = new Complex();
  x.Real = cmp.Real + value;
  x.Imaginary = cmp.Imaginary;
  return x;
 }

and use code like

complex +=5;
于 2010-06-10T15:01:32.030 回答
3

不确定这是否是您想要的,但您可以通过实现隐式运算符来实现:http: //msdn.microsoft.com/en-us/library/z5z9kes2 (VS.71).aspx

于 2010-06-10T14:52:14.647 回答
3

创建一个隐式运算符:

http://msdn.microsoft.com/en-us/library/z5z9kes2.aspx

例如:

public struct MyStruct // I assume this is what you meant, since you mention struct in your title, but use MyClass in your example. 
{
    public MyClass(int i) { val = i; }
    public int val;
    // ...other members

    // User-defined conversion from MyStruct to double
    public static implicit operator int(MyStruct i)
    {
        return i.val;
    }
    //  User-defined conversion from double to Digit
    public static implicit operator MyStruct(int i)
    {
        return new MyStruct(i);
    }
}

“这是一个好主意吗?” 值得商榷。隐式转换往往会破坏程序员公认的标准;通常不是一个好主意。但是,例如,如果您正在做一些大型价值库,那么这可能是一个好主意。

于 2010-06-10T14:52:47.167 回答
0

是的,这是一个简短的例子......

  public struct MyCustomInteger
  {
     private int val;
     private bool isDef;
     public bool HasValue { get { return isDef; } } 
     public int Value { return val; } } 
     private MyCustomInteger() { }
     private MyCustomInteger(int intVal)
     { val = intVal; isDef = true; }
     public static MyCustomInteger Make(int intVal)
     { return new MyCustomInteger(intVal); }
     public static NullInt = new MyCustomInteger();

     public static explicit operator int (MyCustomInteger val)
       { if (!HasValue) throw new ArgumentNullEception();
         return Value; }
     public static implicit operator MyCustomInteger (int val)
       {  return new MyCustomInteger(val); }
  }
于 2010-06-10T14:58:23.247 回答