AS(C#語言符號)

AS(C#語言符號)

as 運算符類似於強制轉換操作;但是,如果轉換不可行,as 會返回 null 而不是引發異常。

基本介紹

  • 中文名:AS
  • 複製代碼:expression is type
  • 相似強制轉換操作
  • 套用:引用轉換和裝箱轉換
基本內容,套用實例,

基本內容

string s = someObject as string;
if (s != null)
{
// someObject is a string.
} 備註
as 運算符類似於強制轉換操作;但是,如果轉換不可行,as 會返回 null 而不是引發異常。更嚴格地說,這種形式的表達式
expression as type等效於
expression is type ? (type)expression : (type)null只是 expression 只被計算一次。
注意,as 運算符只執行引用轉換和裝箱轉換。as 運算符無法執行其他轉換,如用戶定義的轉換,這類轉換應使用 cast 表達式來執行。
示例
// 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 as string;
Console.Write(":", i);
if (s != null)
{
Console.WriteLine("'" + s + "'");
}
else
{
Console.WriteLine("not a string");
}
}
}
}輸出
0:not a string
1:not a string
2:'hello'
3:not a string
4:not a string
5:not a string C# 語言規範
有關更多信息,請參見 C# 語言規範中的以下各章節:
6 轉換
7.9.10 as 運算符

套用實例

Graphics繪圖
JavaScript Code複製內容到剪貼簿
  1. backLayer=newLSprite();
  2. addChild(backLayer);
  3. //畫一圓
  4. backLayer.graphics.drawRect(1,"black",[20,20,150,20],true,"#cccccc");
  5. //畫一個矩形
  6. backLayer.graphics.drawArc(2,"black",[100,100,50,0,2*Math.PI,false],true,"#FF0000");
  7. //畫一條線
  8. backLayer.graphics.drawLine(2,"#FF0000",[200,20,100,50]);

相關詞條

熱門詞條

聯絡我們