今天在研究公司项目框架的时候看到了下面的用法,public static implicit operator JsonData(int data);。貌似很久没用过这种隐式转换的写法了,因此重新温习一下C#中转换相关的知识。

作者:依乐祝

原文地址:https://www.cnblogs.com/yilezhu/p/10898582.html

implicit

implicit 关键字用于声明隐式的用户自定义的类型转换运算符。 如果可以确保转换过程不会造成数据丢失,则可使用该关键字在用户定义类型和其他类型之间进行隐式转换。

使用隐式转换操作符之后,在编译时会跳过异常检查,所以隐式转换运算符应当从不引发异常并且从不丢失信息,否则在运行时会出现一些意想不到的问题。

示例

class Digit
{
public Digit(double d) { val = d; }
public double val;
// ...other members // User-defined conversion from Digit to double
public static implicit operator double(Digit d)
{
return d.val;
}
// User-defined conversion from double to Digit
public static implicit operator Digit(double d)
{
return new Digit(d);
}
} class Program
{
static void Main(string[] args)
{
Digit dig = new Digit(7);
//This call invokes the implicit "double" operator
double num = dig;
//This call invokes the implicit "Digit" operator
Digit dig2 = 12;
Console.WriteLine("num = {0} dig2 = {1}", num, dig2.val);
Console.ReadLine();
}
}

隐式转换可以通过消除不必要的强制转换来提高源代码的可读性。 但是,因为隐式转换不需要程序员将一种类型显式强制转换为另一种类型,所以使用隐式转换时必须格外小心,以免出现意外结果。 一般情况下,隐式转换运算符应当从不引发异常并且从不丢失信息,以便可以在程序员不知晓的情况下安全使用它们。 如果转换运算符不能满足那些条件,则应将其标记为 explicit。 有关详细信息,请参阅使用转换运算符

explicit显示转换

explicit 关键字声明必须通过显示的调用用户定义的类型转换运算符来进行转换。

以下示例定义从 Fahrenheit 类转换为 Celsius 类的运算符。 必须在 Fahrenheit 类或 Celsius 类中定义运算符:

public static explicit operator Celsius(Fahrenheit fahr)
{
return new Celsius((5.0f / 9.0f) * (fahr.Degrees - 32));
}

如下所示,调用用户定义的转换运算符来强制转换:

Fahrenheit fahr = new Fahrenheit(100.0f);
Console.Write($"{fahr.Degrees} Fahrenheit");
Celsius c = (Celsius)fahr;

此转换运算符从源类型转换为目标类型。 源类型提供转换运算符。 不同于隐式转换,显式转换运算符必须通过转换的方式来调用。 如果转换操作会导致异常或丢失信息,则应将其标记为 explicit。 这可阻止编译器静默调用可能产生意外后果的转换操作。

省略转换将导致编译时错误 CS0266。

有关详细信息,请参阅使用转换运算符

示例

下面的示例提供了 FahrenheitCelsius 类,其中每个类均提供转换为其他类的显式转换运算符。

class Celsius
{
public Celsius(float temp)
{
Degrees = temp;
} public float Degrees { get; } public static explicit operator Fahrenheit(Celsius c)
{
return new Fahrenheit((9.0f / 5.0f) * c.Degrees + 32);
}
} class Fahrenheit
{
public Fahrenheit(float temp)
{
Degrees = temp;
} public float Degrees { get; } public static explicit operator Celsius(Fahrenheit fahr)
{
return new Celsius((5.0f / 9.0f) * (fahr.Degrees - 32));
}
} class MainClass
{
static void Main()
{
Fahrenheit fahr = new Fahrenheit(100.0f);
Console.Write($"{fahr.Degrees} Fahrenheit");
Celsius c = (Celsius)fahr; Console.Write($" = {c.Degrees} Celsius");
Fahrenheit fahr2 = (Fahrenheit)c;
Console.WriteLine($" = {fahr2.Degrees} Fahrenheit");
}
}
// 输出:
// 100 Fahrenheit = 37.77778 Celsius = 100 Fahrenheit

示例

下面的示例定义结构 Digit,它表示单个的十进制数字。 将运算符定义为从 byteDigit 的转换,但由于并非所有字节都可转换为 Digit,因此该转换应该应用显式转换。

struct Digit
{
byte value;
public Digit(byte value)
{
if (value > 9)
{
throw new ArgumentException();
}
this.value = value;
} // 定义从byte到Digit的显示转换 explicit operator:
public static explicit operator Digit(byte b)
{
Digit d = new Digit(b);
Console.WriteLine("转换已完成");
return d;
}
} class ExplicitTest
{
static void Main()
{
try
{
byte b = 3;
Digit d = (Digit)b; // 显示转换
}
catch (Exception e)
{
Console.WriteLine("{0} 捕获到一成.", e);
}
}
}
/*
输出:
转换已完成
*/

参考资料

C#中的explicit和implicit了解一下吧的更多相关文章

  1. C#中的Explicit和Implicit

    今天在Review一个老项目的时候,看到一段奇怪的代码. if (dto.Payment == null) continue; var entity = entries.FirstOrDefault( ...

  2. 【RS】CoupledCF: Learning Explicit and Implicit User-item Couplings in Recommendation for Deep Collaborative Filtering-CoupledCF:在推荐系统深度协作过滤中学习显式和隐式的用户物品耦合

    [论文标题]CoupledCF: Learning Explicit and Implicit User-item Couplings in Recommendation for Deep Colla ...

  3. C#中转换运算符explicit、implicit、operator、volatile研究

    C#中的这个几个关键字:explicit.implicit与operator,估计好多人的用不上,什么情况,这是什么?字面解释:explicit:清楚明白的;易于理解的;(说话)清晰的,明确的;直言的 ...

  4. operator、explicit与implicit

    说这个之前先说下什么叫隐式转换和显示转换 1.所谓隐式转换,就是系统默认的转换,其本质是小存储容量数据类型自动转换为大存储容量数据类型. 例如:float f = 1.0: double d=f:这样 ...

  5. explicit和implicit

    explicit是C++中的一个关键字,只用于修饰只有一个参数的构造函数: class A{ explicit A(const T obj); }; 该关键字告诉编译器该类只能显式的转换,不能隐式(i ...

  6. C++中的explicit

    首先, C++中的explicit关键字只能用于修饰只有一个参数的类构造函数, 它的作用是表明该构造函数是显示的, 而非隐式的, 跟它相对应的另一个关键字是implicit, 意思是隐藏的,类构造函数 ...

  7. C++中的explicit关键字的用法

    一.explicit作用: 在C++中,explicit关键字用来修饰类的构造函数,被修饰的构造函数的类,不能发生相应的隐式类型转换,只能以显示的方式进行类型转换. 二.explicit使用注意事项: ...

  8. C++中关键字explicit的作用

    C++中, 一个参数的构造函数(或者除了第一个参数外其余参数都有默认值的多参构造函数), 承担了两个角色. 1 是个构造器 ,2 是个默认且隐含的类型转换操作符. 所以, 有时候在我们写下如 AAA ...

  9. explicit 和 implicit 的用法

    explicit 和 implicit 属于转换运算符,如用这两者可以让我们自定义的类型支持相互交换 explicti 表示显式转换,如从 A -> B 必须进行强制类型转换(B = (B)A) ...

随机推荐

  1. ssh 保持连接

    ssh 保持连接 使用 ssh 登陆到云主机上,一段时间没有操作终端,会发现 ssh 连接断了,终端无响应. 配置 ssh 客户端,使其以一定间隔时间向 sshd 服务端发送心跳包,可解决此问题. / ...

  2. OcelotAPI 简单使用—服务发现、流控

    我这人比较懒 直接上配置文件的图 其中serviceName是服务名称, LoadBalancer是负载均衡策略. 对于流控我为了做测试写的1s 限制5次请求. 剩下的看名字就OK了. 要使用服务发现 ...

  3. 关于erlang中的timer:tc/3

    timer:tc/3对于统计函数运行时间是个很不错的函数, 截图timer:tc/1,tc/2,tc/3的API: 拿斐波那契数列入手做个讲解: -module(fib). -export([fib/ ...

  4. IOS UIScrollView滚动到指定位置

    [mScrollView setContentOffset:CGPointMake(0,200) animated:YES];

  5. C#用Infragistics 导入导出Excel

    最近项目中有数据的导入导出Excel的需求,这里做简单整理. 公司用的是Infragistics的产品,付费,不需要本地安装Office. 有需要的朋友可以下载 Infragistics.2013.2 ...

  6. 九度OJ 1124:Digital Roots(数根) (递归)

    时间限制:1 秒 内存限制:32 兆 特殊判题:否 提交:2963 解决:1066 题目描述: The digital root of a positive integer is found by s ...

  7. aop学习总结二------使用cglib动态代理简单实现aop功能

    aop学习总结二------使用cglib动态代理简单实现aop功能 模拟业务需求: 1.拦截所有业务方法 2.判断用户是否有权限,有权限就允许用户执行业务方法,无权限不允许用户执行业务方法 (判断是 ...

  8. 深入Vue.js从源码开始(二)

    从入口开始 我们之前提到过 Vue.js 构建过程,在 web 应用下,我们来分析 Runtime + Compiler 构建出来的 Vue.js,它的入口是 src/platforms/web/en ...

  9. wait()和notify()

    从https://www.cnblogs.com/toov5/p/9837373.html 可以看到他的打印是一片一片的,这边博客介绍怎么避免掉 使用notify 和 wait的时候 要注意 是在sy ...

  10. x264 --fullhelp

    >x264 --fullhelp x264 core: Syntax: x264 [options] -o outfile infile Infile can be raw (in which ...