C# 中的类型转换

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1339482/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 15:18:39  来源:igfitidea点击:

Typecasting in C#

c#

提问by MAC

What is type casting, what's the use of it? How does it work?

什么是类型转换,它有什么用?它是如何工作的?

采纳答案by Jon Skeet

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 actuallyof a more specific type. For example:

强制转换通常是告诉编译器,虽然它只知道一个值是某种通用类型,但你知道它实际上是一种更具体的类型。例如:

object x = "hello";

...

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

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

有各种转换运算符。该(typename) expression表格可以做三件不同的事情:

  • An unboxing conversion (e.g. from a boxed integer to int)
  • A user-defined conversion (e.g. casting XAttributeto string)
  • A reference conversion within a type hierarchy (e.g. casting objectto string)
  • 拆箱转换(例如从装箱整数到int
  • 用户定义的转换(例如强制转换XAttributestring
  • 类型层次结构中的引用转换(例如强制转换objectstring

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

所有这些都可能在执行时失败,在这种情况下将抛出异常。

The asoperator, on the other hand, never throws an exception - instead, the result of the conversion is nullif it fails:

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

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

There are also implicit conversions, e.g. from intto long:

也有隐式转换,例如从intlong

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

Does that cover everything you were interested in?

这是否涵盖了您感兴趣的所有内容?

回答by Anton Gogolev

See thisor this:

看到这个这个

Because C# is statically-typed at compile time, after a variable is declared, it cannot be declared again or used to store values of another type unless that type is convertible to the variable's type

...

However, you might sometimes need to copy a value into a variable or method parameter of another type. For example, you might have an integer variable that you need to pass to a method whose parameter is typed as double. Or you might need to assign a class variable to a variable of an interface type. These kinds of operations are called type conversions. In C#, you can perform the following kinds of conversions

因为 C# 在编译时是静态类型的,所以在声明变量后,不能再次声明它或用于存储其他类型的值,除非该类型可转换为变量的类型

...

但是,有时您可能需要将值复制到其他类型的变量或方法参数中。例如,您可能有一个整数变量,您需要将其传递给参数类型为 double 的方法。或者您可能需要将类变量分配给接口类型的变量。这些类型的操作称为类型转换。在 C# 中,您可以执行以下类型的转换

回答by rahul

Casting from one data type to another.

从一种数据类型转换为另一种数据类型。

For a general reading see this.

有关一般阅读,请参阅此内容

See also msdn

另请参阅msdn

回答by Richard Watson

Casting means creating a reference to an object that is of a different type to the reference you're currently holding. You can do upcasting or downcasting and each has different benefits.

强制转换意味着创建对与您当前持有的引用类型不同的对象的引用。你可以做向上或向下转换,每个都有不同的好处。

Upcasting:

上行:

string greeting = "Hi Bob";
object o = greeting;

This creates a more general reference (object) from the more specific reference (string). Maybe you've written code that can handle any object, like this:

这从更具体的引用(字符串)创建了一个更通用的引用(对象)。也许您已经编写了可以处理任何对象的代码,如下所示:

Console.WriteLine("Type of o is " + o.GetType());

That code doesn't need to be changed no matter what objects you set o to.

无论您将 o 设置为什么对象,都不需要更改该代码。

Downcasting:

向下转型:

object o = "Hi Bob";
string greeting = (string)o;

Here you want a more specific reference. You might know that the object is a string (you can test this e.g.:

在这里,您需要更具体的参考。您可能知道该对象是一个字符串(您可以对此进行测试,例如:

if (o is string)
{ do something }

Now you can treat the reference as a string instead of an object. E.g. a string has a length (but an object doesn't), so you can say:

现在您可以将引用视为字符串而不是对象。例如,字符串有长度(但对象没有),因此您可以说:

Console.WriteLine("Length of string is " + greeting.length);

Which you can't do with an object.

这是你不能用对象做的。

回答by Cody Winton

Also, if you're explicitly casting, you can take advantage of pattern matching. If you have an object:

此外,如果您要显式转换,则可以利用模式匹配。如果你有一个对象:

object aObject = "My string value";

You can safely cast the object as a string in a single line:

您可以在一行中安全地将对象转换为字符串:

if (aObject is string aString)
{
    Console.WriteLine("aString = " + aString)
    // Output: "aString = My string value"
}

Using this, along with an inverted if statement, you can safely cast types, and fail out early if need be:

使用这个,连同一个倒置的 if 语句,你可以安全地转换类型,并在需要时尽早失败:

public void Conversion(object objA, object objB)
{
    // Fail out early if the objects provided are not the correct type, or are null
    if (!(objA is string str) || !(objB is int num)) { return; }

    // Now, you have `str` and `num` that are safely cast, non-null variables
    // all while maintaining the same scope as your Conversion method
    Console.WriteLine("str.Length is " + str.Length);
    Console.WriteLine("num is " + num);
}