operator - c# symbol
C#中“As”關鍵字的重點是什麼 (5)
來自文檔:
as運算符就像一個轉換,除了它在轉換失敗時產生null而不是引發異常。 更正式地說,表達形式:
expression as type
相當於:
expression is type ? (type)expression : (type) null
除了表達式只被評估一次。
那你為什麼不選擇這樣或那樣做呢? 為什麼有兩個鑄造系統?
效率和績效
執行演員的一部分是一些集成的類型檢查; 因此,使用顯式類型檢查為實際強制轉換添加前綴是多餘的(類型檢查會發生兩次)。 使用as
關鍵字確保只執行一次類型檢查。 您可能會想“但它必須執行空檢查而不是第二次類型檢查”,但與類型檢查相比,空檢查非常有效且高效。
if (x is SomeType )
{
SomeType y = (SomeType )x;
// Do something
}
進行2次檢查,而
SomeType y = x as SomeType;
if (y != null)
{
// Do something
}
生成1x - 與類型檢查相比,空檢查非常便宜。
也許例子會有所幫助:
// Regular casting
Class1 x = new Class1();
Class2 y = (Class2)x; // Throws exception if x doesn't implement or derive from Class2
// Casting with as
Class2 y = x as Class2; // Sets y to null if it can't be casted. Does not work with int to short, for example.
if (y != null)
{
// We can use y
}
// Casting but checking before.
// Only works when boxing/unboxing or casting to base classes/interfaces
if (x is Class2)
{
y = (Class2)x; // Won't fail since we already checked it
// Use y
}
// Casting with try/catch
// Works with int to short, for example. Same as "as"
try
{
y = (Class2)x;
// Use y
}
catch (InvalidCastException ex)
{
// Failed cast
}
它們不是兩個鑄造系統。 兩者有類似的行為,但意義卻截然不同。 “as”表示“我認為這個對象可能實際上屬於另一種類型;如果不是,則給我null。” 演員表示兩件事之一:
我確信這個對象實際上是另一種類型。 這樣做,如果我錯了,請崩潰程序。
我確信這個對像不屬於其他類型,但是有一種眾所周知的方法可以將當前類型的值轉換為所需類型。 (例如,將int轉換為short。)實現它,如果轉換實際上不起作用,則使程序崩潰。
有關詳細信息,請參閱有關該主題的文章。
它允許快速檢查而不需要嘗試/轉換開銷,在某些情況下可能需要處理基於消息的繼承樹。
我使用它很多(收到消息,對特定的子類型做出反應)。 嘗試/施放wouuld要慢得多(每條消息都經過多次嘗試/捕捉幀) - 我們談到在這裡每秒處理200.000條消息。
讓我給你真實世界的場景,你可以在哪裡使用它們。
public class Foo
{
private int m_Member;
public override bool Equals(object obj)
{
// We use 'as' because we are not certain of the type.
var that = obj as Foo;
if (that != null)
{
return this.m_Member == that.m_Member;
}
return false;
}
}
和...
public class Program
{
public static void Main()
{
var form = new Form();
form.Load += Form_Load;
Application.Run(form);
}
private static void Form_Load(object sender, EventArgs args)
{
// We use an explicit cast here because we are certain of the type
// and we want an exception to be thrown if someone attempts to use
// this method in context where sender is not a Form.
var form = (Form)sender;
}
}