什么是类型转换 [英] What is Type Casting
本文介绍了什么是类型转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
任何人都可以消除我的疑虑.
什么是类型转换,以及我们必须在哪里使用?
解决方案
这可能是有关转换的更容易理解的文章: ^ ]
可以使用强制转换显式完成不同数据类型之间的转换.强制转换显式调用从一种类型到另一种类型的转换运算符.如果未定义此类转换运算符,则转换将失败.
在这里阅读:
MSDN:强制转换和类型转换(C#编程指南) [ WikiPedia:类型转换 [ ^ ]
类型转换将变量从一种类型更改为另一种类型,例如从float
到int
.
当您拥有一种类型的对象但需要成为另一种类型的对象时,可以使用它,但是通常可以为您处理,例如,如果您使用过
字符串.Format(" {0} {1} {2}" , 1 , 2 . 3 ," );
String.Format
期望有一个string
和3个object
,但是却给了它一个string
,一个int
,一个float
和另一个string
,因此将最后3个参数强制转换为object
s.
另一个时间是,如果对象显式实现接口,则必须将其强制转换为该接口,然后才能使用该接口的方法.
在这种情况下:
class IntComparer:IComparer< int> { int IComparer< int> .Compare( int x, int y) { 返回 x.CompareTo(y); } }
如果您创建了IntComparer
类型的对象,则只有先将其转换为IComparer<int>
的情况下,Compare
方法才可用,如下所示:
IntComparer c = 新 IntComparer(); c.Compare( 1 , 2 ); // 无效! ((IComparer< int>)c).Compare( 1 , 2 )); // 有效
Can anyone clear my doubt.
What is Type Casting and where we have to use it?
解决方案
This may be a bit more understandable article on casting: http://www.dotnetperls.com/cast[^]
Conversion between different data types can be done explicitly using a cast. A cast explicitly invokes the conversion operator from one type to another. The cast will fail if no such conversion operator is defined.
Have a read here:
MSDN: Casting and Type Conversions (C# Programming Guide)[^]
WikiPedia: Type conversion[^]
Type casting is changing a variable from one type to another, e.g. fromfloat
toint
.
You''d use it when you have an object of one type but you need it to be another, but it is often handled for you, for example if you used
String.Format("{0} {1} {2}", 1, 2.3, "four");
String.Format
is expecting astring
and 3object
s, but it was given astring
, anint
, afloat
, and anotherstring
instead, so the last 3 arguments are cast toobject
s instead.
Another time would be if an object explicitly implements an interface, it must be cast to that interface before the interface''s methods can be used.
Like in this case:
class IntComparer : IComparer<int> { int IComparer<int>.Compare(int x, int y) { return x.CompareTo(y); } }
If you made an object of typeIntComparer
, theCompare
method is only available if you cast it to anIComparer<int>
first, like this:
IntComparer c = new IntComparer(); c.Compare(1,2); // not valid! ((IComparer<int>)c).Compare(1,2); // valid
这篇关于什么是类型转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文