什么是类型转换 [英] What is Type Casting

查看:104
本文介绍了什么是类型转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

任何人都可以消除我的疑虑.
什么是类型转换,以及我们必须在哪里使用?

解决方案

这可能是有关转换的更容易理解的文章: MSDN:强制转换和类型转换(C#编程指南) [ WikiPedia:类型转换 [ ^ ]


类型转换将变量从一种类型更改为另一种类型,例如从floatint.

当您拥有一种类型的对象但需要成为另一种类型的对象时,可以使用它,但是通常可以为您处理,例如,如果您使用过

 字符串.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. from float to int.

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 a string and 3 objects, but it was given a string, an int, a float, and another string instead, so the last 3 arguments are cast to objects 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 type IntComparer, the Compare method is only available if you cast it to an IComparer<int> first, like this:

IntComparer c = new IntComparer();
c.Compare(1,2); // not valid!
((IComparer<int>)c).Compare(1,2); // valid


这篇关于什么是类型转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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