.net 如何隐式地将另一个结构体转换为我的类型?

x7rlezfr  于 2023-03-20  发布在  .NET
关注(0)|答案(4)|浏览(143)

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

cgh8pdjw

cgh8pdjw1#

使用隐式操作符通常被认为是个坏主意,因为它们毕竟是隐式的,并且在你的背后运行。调试充满操作符重载的代码是一场噩梦。也就是说,使用这样的代码:

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;
    }
}

您可以用途:

Complex complex = 10;

或者你可以重载+运算符

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

并使用类似于

complex +=5;
jq6vz3qz

jq6vz3qz2#

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

4uqofj5v

4uqofj5v3#

创建隐式运算符:
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 MyStruct (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);
    }
}

“这是一个好主意吗?”是有争议的。隐式转换倾向于打破程序员可接受的标准;这通常不是一个好主意。但是如果你正在做一些大价值的库,那么这可能是一个好主意。

gajydyqb

gajydyqb4#

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

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); }
  }

相关问题