本文介绍了类型转换在C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么是类型转换,有什么用的呢?它是如何工作的?请提供样品教程..我没有得到从谷歌好。

What is type casting, whats the use of this? How it work? please provide the sample tutorial .. i didnt get good one from google.

推荐答案

铸造通常是告诉,虽然它只是知道一个值是一些通用型的编译器的问题,你知道它的实际一个更具体的类型。例如:

Casting is usually a matter of telling the compiler that although it only knows that a value is of some general type, you know it's actually of a more specific type. For example:

object x = "hello";

...

// I know that x really refers to a string
string y = (string) x;

有各种转换运营商。在(类型名)前pression 的形式可以做三不同的事情:

There are various conversion operators. The (typename) expression form can do three different things:


  • 取消装箱转换(例如,从盒装整数 INT

  • 一个用户定义的转换(例如铸造 XAttribute 字符串

  • 一个类型层次结构中的引用转换(例如铸造对象字符串

  • An unboxing conversion (e.g. from a boxed integer to int)
  • A user-defined conversion (e.g. casting XAttribute to string)
  • A reference conversion within a type hierarchy (e.g. casting object to string)

所有这些可能无法执行时,在这种情况下会抛出异常。

All of these may fail at execution time, in which case an exception will be thrown.

运营商,而另一方面,从不抛出异常 - 相反,转换的结果是如果失败:

The as operator, on the other hand, never throws an exception - instead, the result of the conversion is null if it fails:

object x = new object();
string y = x as string; // Now y is null because x isn't a string

它可用于拆箱到一个空值类型:

It can be used for unboxing to a nullable value type:

object x = 10; // Boxed int
float? y = x as float?; // Now y has a null value because x isn't a boxed float

也有隐式转换,例如从 INT

int x = 10;
long y = x; // Implicit conversion

您是否有兴趣?是面面俱到

Does that cover everything you were interested in?

这篇关于类型转换在C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-22 14:47