我的c#之路(6.类型转换)
来源:互联网 发布:mysql实用教程 pdf 编辑:程序博客网 时间:2024/06/05 19:35
1.
数值转换
-----隐式数值转换
--隐式转换可能在多种情形下发生,包括调用方法时和在赋值语句中。
--数值大小不受影响。
--不存在到char类型的隐式转换。
--不存在浮点型与decimal类型之间的隐式转换。
-----显式数值转换
--显式数值转换用于通过显式转换表达式,将任何数字类型转换为任何其他数字类型,对于它不存在隐式转换。
--显式数值转换可能导致精度损失或引发异常
2.
--隐式转换:由于该转换是一种安全类型的转换,不会导致数据丢失,因此不需要任何特殊的语法。例如,从较小整数类型到较大整数类型的转换以及从派生类到基类的转换都是这样的转换。
int num=2147483647;
long bigNum=num;
对于引用类型,隐式转换始终存在于从一个类转换为该类的任何一个直接或间接的基类或接口的情况
Derived d=new Derived();
Base b=d;//Always OK.
--显式转换(强制转换):显式转换需要强制转换运算符。在转换中可能丢失信息时或在出于其他原因转换可能不成功时,必须进行强制转换。典型的例子包括从数值到精度较低或范围较小的类型的转换和从基类实例到派生类的转换。
double x=1234.7;
int a;
a=(int)x;
对于引用类型,如果需要从基类型转换为派生类型,则必须进行显式强制转换。引用类型之间的强制转换操作不会更改基础对象的运行时类型;它只更改用作对该对象的引用的值得类型。
Animal a=new Animal();
Giraffe g2=(Giraffe)a;
---------------------------------------------------------------------------------------------------------------
使用as和is运算符安全地进行强制转换,由于对象是多态的,因此基类类型的变量可以保存派生类类型。
(若要访问派生类型的方法,需要将值强制转换回该派生类型。不过,在这种情况下,如果只尝试进行简单的强制转换,会导致引发InvalidCastException的风险。这就是C#提供is和as运算符的原因。)
您可以使用这两个运算符来测试强制转换是否会成功,而没有引发异常的风险。通常,as运算符更高效一些,因为如果可以成功进行强制转换,它会实际返回强制转换值。而is运算符只返回一个布尔值。因此,如果只想确定对象的类型,而无需对它进行实际强制转换,则可以使用is运算符。
as运算符类似于强制转换操作。但是,如果无法进行转换,则as返回null而非引发异常。注意,as运算符只执行引用转换和装箱转换。as运算符无法执行其他转换,如用户定义的转换,这类转换应使用强制转换表达式来执行。
--如果需要转化对象的类型属于转换目标类型或者转换目标类型的派生类型时,那么此转换操作才能成功,而且并不产生新的对象(当不成功时返回null),因此用as进行类型转换是安全的。
不用在类型之间进行类型转化
不能应用在值类型数据,即不能如下写(也会出现编译错误):
Object obj1=11;
int nValue=obj1 as int;
应该使用is操作符,再加上老式的类型转换操作,就可以安全完成转换,正确写法如下:
Object obj1=11;
if(objTest is int)
{
int nValue=(int)obj1;
}
--不管是传统的还是as操作符进行类型转换之后,在使用之前,需要进行判断转换是否成功,如下:
if(newValue!=null)
{
//work with the object named "newValue"
}
using System;using System.Collections.Generic;using System.Linq;using System.Text;namespace ConsoleApplication1{ class csrefKeywordsOperators { class Base { public override string ToString() { return "Base"; } } class Derived : Base { public override string ToString() { return "Derived"; } } class Program { static void Main(string[] args) { Derived d = new Derived(); Base b = d as Base; if (b != null) { Console.WriteLine(b.ToString()); } System.Console.ReadKey(); } } }}
---------------------------------------------------------------------------------------------
--使用帮助程序类的转换:若要在不兼容的类型之间进行转换,例如在整数与System.DateTime对象之间转换,或者在十六进制字符串与字节数组之间转换,则可以使用System.BitConverter类、System.Convert类和内置数值类型的Parse方法,例如Int32.Parse。
System.Convert:
using System;using System.Collections.Generic;using System.Linq;using System.Text;namespace ConsoleApplication1{ class Program { static void Main(string[] args) { double dNumber = 23.15; try { //Returns 23 int iNumber = System.Convert.ToInt32(dNumber); } catch (System.OverflowException) { System.Console.WriteLine("Overflow in double to int conversion."); } //Returns True bool bNumber = System.Convert.ToBoolean(dNumber); //Returns "23.15" string strNumber = System.Convert.ToString(dNumber); try { //Returns '2' char chrNumber = System.Convert.ToChar(strNumber[0]); } catch (System.ArgumentNullException) { System.Console.WriteLine("String is null"); } catch (System.FormatException) { System.Console.WriteLine("String length is greater than 1."); } } }}
Int32.Parse:
using System;using System.Collections.Generic;using System.Linq;using System.Text;namespace ConsoleApplication1{ class Program { static void Main(string[] args) { Convert(" 179 "); Convert(" -204 "); Convert(" +809 "); Convert(" 178.3 "); System.Console.ReadKey(); } private static void Convert(string value) { try { int number = Int32.Parse(value); Console.WriteLine("Converted '{0}' to {1}.", value, number); } catch (FormatException) { Console.WriteLine("Unable to convert '{0}'.",value); } } }}// This example displays the following output to the console:// Converted ' 179 ' to 179.// Converted ' -204 ' to -204.// Converted ' +809 ' to 809.// Unable to convert ' 178.3'.
3.
将string转换为int的不同方法
方法一:Convert.ToInt32
ToDecimal(String)、ToSingle(String)、ToDouble(String)、ToInt16(String)、ToInt64(String)、ToUInt16(String)、ToUInt32(String)、ToUInt64(String)
程序将捕捉此方法可能引发的两个最常见的异常。如果该数字可以递增而不溢出整数存储位置,则程序使结果加上1并打印输出。
using System;using System.Collections.Generic;using System.Linq;using System.Text;namespace ConsoleApplication1{ class Program { static void Main(string[] args) { int numVal = -1; bool repeat = true; // while (repeat == true) { Console.WriteLine("Enter a number between -2,147,483,648 and +2,147,483,647(inclusive)."); string input = Console.ReadLine(); //ToInt32 can throw FormatException or OverflowException. try { numVal = Convert.ToInt32(input); } catch (FormatException e) { Console.WriteLine("Input string is not a sequence of digits."); } catch (OverflowException e) { Console.WriteLine("The number cannot fit in an Int32"); } finally { if (numVal < Int32.MaxValue) { Console.WriteLine("The new value is {0}", numVal + 1); } else { Console.WriteLine("numVal cannot be incremented beyond its current value"); } } Console.WriteLine("Go again?Y/N"); string go = Console.ReadLine(); if (go == "Y" || go == "y") { repeat = true; } else { repeat = false; } } Console.ReadKey(); } }}
方法二:Int32.Parse Int32.TryParse
如果字符串的格式无效,则Parse会引发一个异常;TryParse不会引发异常,但会返回false。下面的示例演示了对Parse和TryParse的成功调用和不成功的调用。
int numVal=Int32.Parse("-105");
Console.WriteLine(numVal);
//Output:-105
int j;
bool result=Int32.TryParse("-105",out j);
if(true==result)
{
Console.WriteLine(j);
}
else
{
Console.WriteLine("String could not be parsed.");
}
//Output:-105
try
{
int m=Int32.Parse("abc");
}
catch(FormatException e)
{
Console.WriteLine(e.Message);
}
//Output:Input string was not in a correct format.
string inputString="abc";
int numValue;
bool parsed=Int32.TryParse(inputString,out numValue);
if(!parsed)
{
Console.WriteLine("Int32.TryParse could not parse '{0}' to an int.\n",inputString);
}
//Output:Int32.TryParse could not parse 'abc' to an int.
4.
--确定字符串是否表示数值
静态的TryParse方法:如果字符串包含非数值字符或者所包含的数值对于指定的特定类型而言太大或太小,TryParse都将返回false并将out参数设置为零。
否则,它将返回true,并且将out参数设置为字符串的数值。
string numString ="1287543";//"1287543.0" will return false for a long
long number1=0;
bool canConvert=long.TryParse(numString,out number1);
if(canConvert==true)
{
Console.WriteLine("number1 now={0}",number1);
}
else
{
Console.WriteLine("numString is not a valid long");
}
byte number2=0;
numString="255";//A value of 256 will return false
canConvert=byte.TryParse(numString,out number2);
if(canConvert==true)
{
Console.WriteLine("number2 now={0}",number2);
}
else
{
Console.WriteLine("numString is not a valid byte");
}
decimal number3=0;
numString="27.3";//"27" is also a valid decimal
canConvert=decimal.TryParse(numString,out number3);
if(canConvert==true)
{
Console.WriteLine("number3 now={0}",number3);
}
else
{
Console.WriteLine("number3 is not a valid decimal");
}
5.
--在c#中提供的很好的类型转换方式总结为:
Object=>已知引用类型-------使用as操作符完成;
Object=>已知值类型--------先使用is操作符来进行判断,再使用类型强制转换方式进行转换;
已知引用类型之间转换-------首先需要相应类型提供转换函数,再用类型强制转换方式进行转换;
已知值类型之间转换-------最好使用系统提供的Conver类所涉及的静态方法;
- 我的c#之路(6.类型转换)
- C#之类型转换
- c#之类型转换
- C#之类型转换
- C# 的类型转换
- C#的类型转换
- C#的类型转换
- C#的类型转换
- C#的类型转换
- C#类型的转换
- C#的类型转换
- C#的类型转换
- C#日积月累之类型转换
- c#之类型转换2
- C#基础之类型转换
- 我的c#之路
- C#的强制类型转换
- C#输入的类型转换
- adobe reader页面背景色设置 编辑--首选项--辅助工具--文档颜色--自定义颜
- 大数据量高效率去重复数据
- 将博客搬至CSDN
- ImportError: No module named setuptools 解决方案
- 地图API公交线路查询
- 我的c#之路(6.类型转换)
- JAVA安卓开发第二天
- 快速摸清一个行业的基本情况
- 淘宝的行癲时代(上)
- IOS调用相机相册(1)
- POI3.8中 大数据量的处理
- 《C++ Primer第四版》学习笔记(五)变量和基本类型 之 变量
- oracle 错误 access violation at address in module 'ora805.dll'. write of address
- Sciter笔记- 1