隐式运算符 [英] implicit operator

查看:85
本文介绍了隐式运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚看到它在最近的答案之一中使用:

I just saw it was using in one of the recent answers:

public static implicit operator bool(Savepoint sp)
{
    return sp != null;
}

为什么我们在这里需要隐含词 ,这是什么意思?

Why do we need word implicit here, and what does it mean?

推荐答案

隐含表示转换不需要在代码中进行强制转换.

Implicit means that the conversion doesn't require a cast in your code.

您现在可以执行以下操作:

You can now do this:

Savepoint point = new Savepoint();
if(point) // becomes a bool using your operator
{
}

不必这样做:

Savepoint point = new Savepoint();
if((bool)point) // an "explicit" conversion
{
}

为什么这是一个有用的区别的一个例子是数字类型.从较小"​​类型到较大"类型的隐式转换,例如:

One example of why this is a useful distinction is numeric types. There's an implicit conversion from "smaller" types to "larger" types, e.g:

float f = 6.5;
double d = f; // implicit conversion

但是将较大的类型转换为较小的类型可能很危险,因此只能进行显式转换,从而迫使用户明确说明他确实打算执行相关操作:

But converting larger types to smaller types can be dangerous, so there's only an explicit conversion, forcing the user to clarify that he really intends to perform the operation in question:

long l = 20;
// short s = l;
short s = (short)l;  // explicit conversion

这篇关于隐式运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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