如何将另一个结构隐式转换为我的类型?
既然是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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
通常认为使用隐式运算符是一个坏主意,因为它们毕竟是隐式的并且在您背后运行。调试充满运算符重载的代码是一场噩梦。也就是说,对于这样的事情:
您可以使用:
或者您可以重载 + 运算符
并使用类似的代码
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:
you could use:
or you could ever overload the + operator
and use code like
不确定这是否是您想要的,但您可以通过实现隐式运算符来实现:
http://msdn.microsoft.com/en-us /library/z5z9kes2(VS.71).aspx
Not sure if this is what you want but you may get there by implementing the implicit operator:
http://msdn.microsoft.com/en-us/library/z5z9kes2(VS.71).aspx
创建隐式运算符:
http://msdn.microsoft.com/en-us /library/z5z9kes2.aspx
例如:
“这是个好主意吗?”是有争议的。隐式转换往往会违反程序员公认的标准;通常不是一个好主意。但是,例如,如果您正在创建一些大型价值库,那么这可能是一个好主意。
Create an implicit operator:
http://msdn.microsoft.com/en-us/library/z5z9kes2.aspx
For example:
"Is this a good idea?" is debatable. Implicit conversions tend to break accepted standards for programmers; generally not a good idea. But if you're doing some large value library, for example, then it might be a good idea.
是的,这是一个简短的例子......
yes, here's a short example ...