在C Sharp中进行投放管理的最佳做法 [英] Best practice for casting in c sharp

查看:47
本文介绍了在C Sharp中进行投放管理的最佳做法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好,我只是想知道铸造的最佳实践是什么.
示例;

Hi im just wondering what the best practice for casting is.
Example;

int MyInt = (int)SomeVariable;
int MyInt = Convert.ToInt32(SomeVariable);



在此先感谢



Thanks in advance

推荐答案

请参阅链接
浇铸和类型转换
see link
Casting and Type Conversions


您有两点不同.
You have two different things.
// 1. a cast
int MyInt = (int)SomeVariable;


SomeVariable必须是可以直接转换为整数(即​​为整数或具有整数部分的数字,字符或字节)的类型.从float或double进行转换意味着您会丢失小数部分,但这有时很有用.


SomeVariable needs to be a type that can directly cast to an integer, i.e. a numeric, character or byte which is or has an integral part. Casting from float or double means you lose the fractional part, but that is useful at times.

// 2. converter
int MyInt = Convert.ToInt32(SomeVariable);


在这种情况下,您将获取一个不能直接引用为数字的值(例如,诸如"1378"之类的字符串),并将其解析为其组成部分并转换为它表示的值.


In this case you are taking a value which cannot be directly referenced as a number (e.g. a string such as "1378") and parsing it into its constituent parts and converting to the value it represents.


您也可以使用Int32.TryParse,如果可能的话,您可以进行转换,并返回一个指示成功/失败的布尔值.
You can also use Int32.TryParse which allows you to convert if it''s possible, and return a bool indicating success/failure.


这篇关于在C Sharp中进行投放管理的最佳做法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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