Jon*_*eet 64
转换通常是告诉编译器虽然它只知道某个值是某种通用类型的问题,但您知道它实际上是更具体的类型.例如:
object x = "hello";
...
// I know that x really refers to a string
string y = (string) x;
Run Code Online (Sandbox Code Playgroud)
有各种转换运算符.该(typename) expression表格可以做三件不同的事情:
int)XAttribute为string)object为string)所有这些都可能在执行时失败,在这种情况下将抛出异常.
该as运营商,在另一方面,从不抛出异常-相反,转换的结果是null,如果它失败:
object x = new object();
string y = x as string; // Now y is null because x isn't a string
Run Code Online (Sandbox Code Playgroud)
它可用于取消装箱到可以为空的值类型:
object x = 10; // Boxed int
float? y = x as float?; // Now y has a null value because x isn't a boxed float
Run Code Online (Sandbox Code Playgroud)
也有隐式转换,例如从int到long:
int x = 10;
long y = x; // Implicit conversion
Run Code Online (Sandbox Code Playgroud)
这涵盖了您感兴趣的一切吗?