简体   繁体   English

C#-转换-澄清

[英]C# - Conversion -Clarification

This could be a very basic question for prodigies.But I have a doubt to handle it. 对于神童来说,这可能是一个非常基本的问题,但我对此有疑问。

During Conversion we are using : 在转换期间,我们使用:

int.Parse(someThing) int.Parse(someThing)
Convert.ToInt32 or Convert.ToString().... Convert.ToInt32或Convert.ToString()....

(Int32)(someValue) (Int32)(someValue)

even we use "as" 即使我们使用“ as”

What are the restrictions for using each? 每种使用有哪些限制?

int.Parse assumes a string as a parameter and as such is only suitable for converting raw string representations to integers int.Parse假定字符串为参数,因此仅适用于将原始字符串表示形式转换为整数

Convert.ToInt32() will attempt to convert pretty much any object to an integer representation. Convert.ToInt32()将尝试将几乎所有对象转换为整数表示形式。 Where the representation isn't a valid int (ie using a float with the value 55.3 or a string containing a word) this will raise a FormatException. 如果表示形式不是有效的int(即使用值为55.3的浮点数或包含单词的字符串),则将引发FormatException。 If the integer is too large to fit in an int then an OverflowException will occur. 如果整数太大而不能容纳在int中,则将发生OverflowException。

(int) is a direct cast. (int)是直接转换。 It's basically saying "I know that this object is really an integer, treat it as such". 基本上是说“我知道这个对象实际上是一个整数,将其视为此类”。 If the object actually isnt an integer you'll get an invalid cast exception. 如果对象实际上不是整数,则将获得无效的强制转换异常。

Finally, as behaves the same as a direct cast except where the object is not of the correct type it will assign null. 最后,as的行为与直接转换相同,不同之处在于对象的类型不正确时,它将分配null。 Not sure how this applies to int with it being a non-nullable type but certainly usable with 不知道int是不可为空的类型,但肯定可以将其用于int

int? myInt = someVar as int?;

Convert.ToNnnn has the restrictions stipulated by its overloads; Convert.ToNnnn具有其重载所规定的限制; for instance, you cannot call Convert.ToMyCustomType (since that method does not exist). 例如,您不能调用Convert.ToMyCustomType (因为该方法不存在)。 You can pass pretty much anything into Convert.ToString (or Convert.ToInt32 or any other of the Convert.ToNnnn methods) but the result may not always make sense. 您可以将几乎所有内容传递给Convert.ToString (或Convert.ToInt32或任何其他Convert.ToNnnn方法),但结果可能并不总是有意义。 Also, if the method fails to perform the conversion it may throw an InvalidCastException . 另外,如果方法无法执行转换,则可能抛出InvalidCastException

The regular type case ( (int)someValue ) can be used in all cases where there is an explicit conversion available. 常规类型的大小写( (int)someValue )可以在所有有显式转换可用的情况下使用。 If you try to perform an illegal cast you will get an exception thrown at you. 如果您尝试执行非法投射,则会抛出异常。

The as keyword can be used to cast type to another (reference) type (and it will return null if it's not possible). as关键字可用于将类型转换为其他(引用)类型(如果不可能,它将返回null)。 The as keyword cannot be used with value types (such as Int32 , Point or DateTime ). as关键字不能与值类型(例如Int32PointDateTime )一起使用。

In my own code I typically use a mixture of them, but in general I follow the following scheme: 在我自己的代码中,我通常将它们混合使用,但是通常我遵循以下方案:

  • If I want to convert a string to a numeric type, I usually use the TryParse provided by that numeric type. 如果要将字符串转换为数字类型,通常会使用该数字类型提供的TryParse
  • If I want to cast a class instance to a base class or interface, I usually use the as keyword. 如果我想将类实例转换为基类或接口,则通常使用as关键字。
  • In other cases I use regular type casting within try/catch blocks. 在其他情况下,我在try/catch块中使用常规类型转换。

Convert.ToInt32 can convert from various types (DateTime, Decimal, etc) back to an integer, while int.Parse() only converts from a string. Convert.ToInt32可以从各种类型(DateTime,Decimal等)转换回整数,而int.Parse()仅从字符串转换。

If you're only parsing strings back to integers, Convert.ToInt32 is just an alias for int.Parse , so you might as well use int.Parse instead. 如果仅将字符串解析为整数,那么Convert.ToInt32只是int.Parse的别名,因此您最好使用int.Parse

Regarding casting, you cannot cast a string to an integer, you have to convert it like mentioned above. 关于强制转换,您不能将字符串强制转换为整数,必须像上面提到的那样转换

Consider that you are working with a database, and you have a column that is inefficiently declared as varchar while it stores integer data. 考虑到您正在使用数据库,并且有一列在存储整数数据时被低效率地声明为varchar You cannot do (int)dr["column"] when using a SqlDataReader for instance, you would have to use int.Parse(dr["column"].ToString()) instead. 例如,在使用SqlDataReader时,不能执行(int)dr["column"] ,而必须使用int.Parse(dr["column"].ToString()) If the column was of the int column type in the database, you could then have used the cast: (int)dr["column"] . 如果该列是数据库中的int列类型,则可以使用强制转换: (int)dr["column"]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM