Menu
×
   ❮   
HTML CSS JAVASCRIPT SQL PYTHON JAVA PHP HOW TO W3.CSS C C++ C# BOOTSTRAP REACT MYSQL JQUERY EXCEL XML DJANGO NUMPY PANDAS NODEJS R TYPESCRIPT ANGULAR GIT POSTGRESQL MONGODB ASP AI GO KOTLIN SASS VUE DSA GEN AI SCIPY AWS CYBERSECURITY DATA SCIENCE
     ❯   

C# 类型转换


C# 类型转换

类型转换是指将一个数据类型的值赋给另一个类型。

在 C# 中,有两种类型的转换

  • 隐式转换(自动) - 将较小的类型转换为较大的类型大小
    char -> int -> long -> float -> double

  • 显式转换(手动) - 将较大的类型转换为较小的类型大小
    double -> float -> long -> int -> char

隐式转换

当将较小尺寸的类型传递给较大尺寸的类型时,会自动执行隐式转换。

示例

int myInt = 9;
double myDouble = myInt;       // Automatic casting: int to double

Console.WriteLine(myInt);      // Outputs 9
Console.WriteLine(myDouble);   // Outputs 9

自己动手试试 »


显式转换

显式转换必须手动完成,方法是在值前面用括号括起来指定类型。

示例

double myDouble = 9.78;
int myInt = (int) myDouble;    // Manual casting: double to int

Console.WriteLine(myDouble);   // Outputs 9.78
Console.WriteLine(myInt);      // Outputs 9

自己动手试试 »


类型转换方法

还可以使用内置方法显式转换数据类型,例如 Convert.ToBooleanConvert.ToDoubleConvert.ToStringConvert.ToInt32 (int) 和 Convert.ToInt64 (long)

示例

int myInt = 10;
double myDouble = 5.25;
bool myBool = true;

Console.WriteLine(Convert.ToString(myInt));    // convert int to string
Console.WriteLine(Convert.ToDouble(myInt));    // convert int to double
Console.WriteLine(Convert.ToInt32(myDouble));  // convert double to int
Console.WriteLine(Convert.ToString(myBool));   // convert bool to string

自己动手试试 »

为什么要转换?

很多时候,不需要进行类型转换。但有时你必须这样做。在下一章中,在处理 用户输入 时,查看一个这方面的例子。


×

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail:
[email protected]

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail:
[email protected]

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Copyright 1999-2024 by Refsnes Data. All Rights Reserved. W3Schools is Powered by W3.CSS.