C# 中的 Convert.ChangeType 方法

csharpprogrammingserver side programming

ChangeType() 方法返回指定类型的对象,其值等于指定对象。

假设我们有一个 double 类型。

double val = -3.456

现在,使用 ChangeType 方法将类型更改为整数。

num = (int)Convert.ChangeType(val, TypeCode.Int32);

让我们看一下完整的例子。

示例

using System;
public class Demo {
   public static void Main() {
      double val = -3.456;
      int num = (int)Convert.ChangeType(val, TypeCode.Int32);
      Console.WriteLine("{0} converted to an Int32: {1}", val, num);
   }
}

输出

-3.456 converted to an Int32: -3

相关文章