在C Sharp中进行投放管理的最佳做法

在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.