我怎么能隐式转换另一种结构来我喜欢的类型? [英] How can I implicitly convert another struct to my Type?

查看:126
本文介绍了我怎么能隐式转换另一种结构来我喜欢的类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于它是 MyClass的X = 120; ,是有可能创造这样一个自定义类? 如果是这样,我该怎么办呢?

As it is MyClass x = 120;, is it possible to create such a custom class? If so, how can I do that?

推荐答案

它通常被认为是一个坏主意,使用隐式的经营者,因为他们毕竟是隐式和运行在你的背后。调试code散落着运算符重载是一场噩梦。这就是说,像这样的东西:

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

您可以使用:

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

和使用code像

complex +=5;

这篇关于我怎么能隐式转换另一种结构来我喜欢的类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆