当前位置:网站首页>C # use the default transformation method
C # use the default transformation method
2022-07-26 20:08:00 【biyusr】
*This article is about
《 Write high quality code to improve C# programmatic 157 A suggestion 》Chapter oneBasic language elementsSuggestions for 2Use the default transformation method, If you like this book, please buy the original book in major shopping malls , Support genuine .
In addition to string operations , The second problem commonly encountered by programmers is : How to transform types correctly . In the previous suggestion , from int Transformation into string, We used type int Of ToString Method . In most cases , When need is right FCL When transforming the type provided , Should be used FCL Transformation methods provided .
These transformation methods include :
Use type conversion operators .
Use the built-in Parse、TryParse, Or as ToString、ToDouble、 and ToDateTime Other methods .
Use the methods provided by the help class .
Use CLR Supported transformation .
These methods are described below .
1. Use the conversion operator of type
Use type conversion operators , In fact, it is to use a method inside the type ( It's a function ). There are two types of conversion operators : Hidden and explicit conversions ( Coercive transformation ). Primitive types generally provide conversion operators , Such as :
int i = 0;
float j = 0;
j = i; // int To float(Single) There is an implicit transformation
i = (int)j; // float(Single) To int There is , And there must be an explicit conversion
*Be careful So-called “ Primitive type ”, Data types directly supported by the compiler , That is, directly map to FCL The type of . Primitive types include sbyte、byte、short、ushort、int、uint、long、ulong、char、float、double、bool、decimal、object、string.
User defined types can also provide this kind of conversion by overloading conversion operators , The code is as follows :
class Program
{
static void Main(string[] args)
{
IP ip = "192.168.0.1";
Console.WriteLine(ip.ToString());
}
}
class IP
{
IPAddress value;
public IP(string ip)
{
value = IPAddress.Parse(ip);
}
public static implicit operator IP(string ip)
{
IP iptemp = new IP(ip);
return iptemp;
}
public override string ToString()
{
return value.ToString();
}
}
In the code above IP ip = "192.168.0.1"; What is provided is the string to IP The implicit transformation between . however , Unless you consider some initial values , It is generally not recommended that users overload conversion operators for their own types . If you need to convert between user-defined types , It is suggested to consider from an object-oriented perspective , Because they usually contain some kind of relationship ( Such as inheritance 、 To achieve, etc ). under these circumstances , You should use the fourth method that will be introduced :CLR Supported transformation . however , We still need to master FCL The type of , Especially the conversion operators between primitive types , In order to quickly convert primitive types .
2. Use the built-in Parse、TryParse, Or as ToString、ToDouble、ToDateTime Other methods
stay FCL in , If a certain type often needs transformation , The type itself has some transformation methods . For instance from string Transformation into int, Because it happens all the time , therefore int In itself, it provides Parse and TryParse Method . In general , If you want to convert a type , It is recommended to check this type of API file .
3. Use the methods provided by the help class
It can be used as System.Convert class 、System.BitConverter Class for type conversion .
System.Covnert Provides a method to convert a primitive type to another type , Such as ToChar、ToBoolean Such method . It is worth noting that ,System.Convert It also supports converting any custom type to any primitive type , As long as the custom type inherits IConvertible Interface will do . As in the above IP class , If you will IP Transformation into string, In addition to rewriting Object Of ToString Outside method , It can also be realized IConvertible Of ToString Method , The code is as follows :
class IP:IConvertible
{
// Omit
public bool ToBoolean(IFormatProvider provider)
{
throw new InvalidCastException("IP-to-Boolean conversion is not supported.");
}
public override string ToString()
{
return value.ToString();
}
// Omit
}
Inherit IConvertible Interfaces must implement other transformation methods at the same time , As in the above ToBoolean, If this transformation is not supported , You should throw a InvalidCastException, Instead of a NotImplementedException.
System.BitConverter It provides a method to convert primitive types to byte arrays , No more details here .
4. Use CLR Supported transformation
CLR Supported transformation , That is, upward transformation and downward transformation . The first thing about this concept is Java The one mentioned in , In fact, it is the conversion between the base class and the subclass , As shown in the figure :

Class inheritance
Implicit transformation is supported in the transformation from subclass to base class , Such as Dog Obviously it's a Animal; And when Animal Transformation into Dog When , Must be an explicit conversion , because Animal It could be a Cat, The code is as follows :
Animal animal;
Dog dog = new Dog();
animal = dog; // Hide transformation , because Dog Namely Animal
// dog = animal; // Compile not pass
dog = (Dog)animal; // There must be an explicit transformation 边栏推荐
- cv2.resize()
- Docker使用mysql:5.6和 owncloud 镜像,构建一个个人网盘,安装搭建私有仓库 Harbor
- 负载均衡的使用
- 低代码工具有哪些特色?明眼人都能看出来的低代码两大发展轨迹!
- C#异步编程看这篇就够了
- 有点酷,使用 .NET MAUI 探索太空
- [PHP] MySQL native PHP operation - Tianlong eight steps
- Codeforces Round #810 (Div. 2)(A~C)
- 使用请求头认证来测试需要授权的 API 接口
- Design of intelligent weighing system based on Huawei cloud IOT (STM32) [i]
猜你喜欢

开源闹出乌龙事件,可能你不知道这五种开源协议

ShardingSphere-JDBC 关键字问题

使用ECS和OSS搭建个人网盘

Training embedded representation of large categories using triple loss and twin neural networks

These 22 drawing (visualization) methods are very important and worth collecting!

Where can I find the files downloaded from iPad

以 NFT 为抵押品的借贷协议模式探讨

猎聘问卷星,成为微信「寄生虫」

Decompile jar files (idea environment)

Digital transformation of enterprises has become a general trend, and it is important to choose the right online collaboration tools
随机推荐
Excel-VBA 快速上手(十、提示框、可输入的弹出框)
u盘损坏怎么恢复原来数据,u盘损坏数据如何恢复
千亿酸奶赛道,乳企巨头和新品牌打响拉锯战
C#异步编程看这篇就够了
企业内部信息碎片化该怎么办?不妨试试这样做
three.js 制作地球标注的两种方法
Intensive reading of the paper: yolov2 - yolo9000: better, faster, stronger
【PHP】MySQL原生PHP操作-天龙八步
Kingbases SQL language reference manual of Jincang database (14. SQL statement: commit to create language)
[shell] Reprint: batch replacement find awk sed xargs
猎聘问卷星,成为微信「寄生虫」
花1200亿修一条“地铁”,连接4个万亿城市,广东在想啥?
How to adjust the abnormal win11 USB drive to normal?
What should we do about the fragmentation of internal information? Try this
事务回滚,同时记录异常信息
中天钢铁在 GPS、 AIS 调度中使用 TDengine
数据库笔记(来自老社)
移动端video兼容你需要知道的几点
【OBS】解决OBS推两个rtmp流 + 带时间戳问题
Software testing - what are the automated testing frameworks?