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

来源:互联网 发布:民国 知乎 编辑:程序博客网 时间:2024/05/16 17:07
文明人  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)这种方式通过在具体自定义类型中的可以通过改写其方法使用
原创粉丝点击