你有一些真正的基本概念,你試圖去理解。我會嘗試打破這個問題並澄清一些問題,並添加到您收到的兩個特殊答案中。
演員:
的鑄造概念概念是非常重要的,因爲這個概念是在你的數據的修改勢在必行。你的具體問:
Explicit conversions (casts): Explicit conversions require a cast operator. Casting is required when information might be lost in the conversion, or when the conversion might not succeed for other reasons. Typical examples include numeric conversion to a type that has less precision or a smaller range, and conversion of a base-class instance to a derived class.
在你的例子中,你的實施as Rectangle
。爲了簡單起見,我將使用更簡單的數據類型。該as
投當它轉換它不會產生以下錯誤:
相反,當它失敗,這是一個乾淨的方式默默地失敗則返回null
。在某些情況下,您不希望異常中斷您的用戶流,從而滿足特定需求。
實施例(A):
int valid = 0;
string number = valid as string;
實施例(B):
string valid = 1;
int number = valid as string;
實施例(C):
string valid = "valid";
int? number = valid as int?;
所有三種的那些考試普萊斯是有效的,但在例(C)你會注意到兩個項目:
int?
- 允許一個int
一個null
。
- 它也不會破壞你的應用程序,因爲失敗的轉換將返回
null
。
爲鑄造另一種方法是應用(int)
或(string)
的數據明確強制到類型。所以它會或者成功和或者拋出異常。例如:
實施例(d):
string invalid = "Fail"
int? number = (int?)invalid;
這將導致無效轉換異常被拋出。 實例(C)和實例(D)是鑄造之間的差異的兩個簡單比較。
希望這可以爲您提供更好的信息。
所以你有一個工作代碼,並想知道它爲什麼有效?你有沒有試過在C#_中搜索_as運算符? –