📜  C#-类型转换

📅  最后修改于: 2020-12-28 05:00:27             🧑  作者: Mango


类型转换将一种类型的数据转换为另一种类型。也称为类型转换。在C#中,类型转换具有两种形式-

  • 隐式类型转换-这些转换由C#以类型安全的方式执行。例如,是从较小的整数类型到较大的整数类型的转换,以及从派生类到基类的转换。

  • 显式类型转换-这些转换由用户使用预定义的函数显式完成。显式转换需要强制转换运算符。

以下示例显示了显式类型转换-

using System;

namespace TypeConversionApplication {
   class ExplicitConversion {
      static void Main(string[] args) {
         double d = 5673.74; 
         int i;
         
         // cast double to int.
         i = (int)d;
         Console.WriteLine(i);
         Console.ReadKey();
      }
   }
}

编译并执行上述代码后,将产生以下结果-

5673

C#类型转换方法

C#提供以下内置类型转换方法-

Sr.No. Methods & Description
1

ToBoolean

Converts a type to a Boolean value, where possible.

2

ToByte

Converts a type to a byte.

3

ToChar

Converts a type to a single Unicode character, where possible.

4

ToDateTime

Converts a type (integer or string type) to date-time structures.

5

ToDecimal

Converts a floating point or integer type to a decimal type.

6

ToDouble

Converts a type to a double type.

7

ToInt16

Converts a type to a 16-bit integer.

8

ToInt32

Converts a type to a 32-bit integer.

9

ToInt64

Converts a type to a 64-bit integer.

10

ToSbyte

Converts a type to a signed byte type.

11

ToSingle

Converts a type to a small floating point number.

12

ToString

Converts a type to a string.

13

ToType

Converts a type to a specified type.

14

ToUInt16

Converts a type to an unsigned int type.

15

ToUInt32

Converts a type to an unsigned long type.

16

ToUInt64

Converts a type to an unsigned big integer.

以下示例将各种值类型转换为字符串类型-

using System;

namespace TypeConversionApplication {
   class StringConversion {
      static void Main(string[] args) {
         int i = 75;
         float f = 53.005f;
         double d = 2345.7652;
         bool b = true;

         Console.WriteLine(i.ToString());
         Console.WriteLine(f.ToString());
         Console.WriteLine(d.ToString());
         Console.WriteLine(b.ToString());
         Console.ReadKey();
            
      }
   }
}

编译并执行上述代码后,将产生以下结果-

75
53.005
2345.7652
True