你有一些真正的基本概念,你试图去理解。我会尝试打破这个问题并澄清一些问题,并添加到您收到的两个特殊答案中。
演员:
的铸造概念概念是非常重要的,因为这个概念是在你的数据的修改势在必行。你的具体问:
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运算符? –