cast 转换类型 C# as () 区别 -----------更优雅的类型转换

文明人  as 

as 运算符类似于强制转换操作。但是,如果无法进行转换,则 as 返回 null 而非引发异常。请看下面的表达式:




比较强硬   ,,,, 一旦失败可能是程序终止,但是有时候是必要....
core component is  error   we must be stop it . 

try{

    = () 强转  

}catch (){

}

如果是 可选的 组件 出了问题 
if   an option   component is  error ,we can  backup  method ....

string s = someObject as string;
if (s != null)
{
// someObject is a string.
}




   例子来自 c# msdn 规范 




//  cs_keyword_as.cs
//  The as operator.
using  System;
class  Class1
{
}

class  Class2
{
}

class  MainClass
{
    
static   void  Main()
    {
        
object [] objArray  =   new   object [ 6 ];
        objArray[
0 =   new  Class1();
        objArray[
1 =   new  Class2();
        objArray[
2 =   " hello " ;
        objArray[
3 =   123 ;
        objArray[
4 =   123.4 ;
        objArray[
5 =   null ;

        
for  ( int  i  =   0 ; i  <  objArray.Length;  ++ i)
        {
            
string  s  =  objArray[i]  as   string ;
            Console.Write(
" {0}: " , i);
            
if  (s  !=   null )
            {
                Console.WriteLine(
" ' "   +  s  +   " ' " );
            }
            
else
            {
                Console.WriteLine(
" not a string " );
            }
        }
    }
}





另附
来自csdn


第一种:Convert.ToInt32(stringVal) 
第二种:(string)intVal 
---------------------------------------------- 
1.把stringVal强制转换为一个int型数据,此方法为Convert类的方法,不允许被重载。 
2.把intVal转换为string型返回一个string类型对象。 

在基本数据类型当中,这两种表达方式将执行一致的操作返回一致的结果集 
他们的主要区别主要在自定义类型当中,Convert.ToInt32()这种方式不能适用于自定义类型 
而(string)这种方式通过在具体自定义类型中的可以通过改写其方法使用
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值