JUST DO IT ~

我只想当个程序员

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

() java 中来的类型转换 . 转换不成 就爆发异常..

文明人  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)这种方式通过在具体自定义类型中的可以通过改写其方法使用

posted on 2008-08-31 09:27 小高 阅读(1657) 评论(0)  编辑  收藏 所属分类: DotNet


只有注册用户登录后才能发表评论。


网站导航:
 

导航

<2008年8月>
272829303112
3456789
10111213141516
17181920212223
24252627282930
31123456

统计

常用链接

留言簿(3)

随笔分类(352)

收藏夹(19)

关注的blog

手册

搜索

积分与排名

最新评论

阅读排行榜

评论排行榜