() java 中來的類型轉(zhuǎn)換 . 轉(zhuǎn)換不成 就爆發(fā)異常..
文明人 as
as 運算符類似于強制轉(zhuǎn)換操作。但是,如果無法進行轉(zhuǎn)換,則 as 返回 null 而非引發(fā)異常。請看下面的表達式:
比較強硬 ,,,, 一旦失敗可能是程序終止,但是有時候是必要....
core component is error we must be stop it .
try{
= () 強轉(zhuǎn)
}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 規(guī)范
// 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強制轉(zhuǎn)換為一個int型數(shù)據(jù),此方法為Convert類的方法,不允許被重載。
2.把intVal轉(zhuǎn)換為string型返回一個string類型對象。
在基本數(shù)據(jù)類型當中,這兩種表達方式將執(zhí)行一致的操作返回一致的結(jié)果集
他們的主要區(qū)別主要在自定義類型當中,Convert.ToInt32()這種方式不能適用于自定義類型
而(string)這種方式通過在具體自定義類型中的可以通過改寫其方法使用