c# - 使用参数转换数据类型 - ChangeType() 范围问题

标签 c# .net collections

我想根据另一个变量的类型转换一个变量。

这样做的原因是我有一个扩展方法,它将对 T 应用计算,前提是 T 是 double 、 float 或小数(我在方法开头测试正确的类型)。

所以无论如何,使用以下代码片段测试转换会引发错误:

      List<double> source = new List<double>();
      source.Add(1);
      Type typ = source.First().GetType();
      var newVal = Convert.ChangeType(source.First(), typeof(typ));  //error: typ not found

The type or namespace name 'typ' could not be found (are you missing a using directive or an assembly reference?)

但是,这工作正常:

      List<double> source = new List<double>();
      source.Add(1);
      Type typ = source.First().GetType();
      var newVal = Convert.ChangeType(source.First(), typeof(double));

最佳答案

请注意,Type 对象和对类​​型的引用不是同一件事。

虽然 Type typ 创建了 Type 类型的对象,但是 typeof(T) 返回了一个 基于编译时已知的 T 类型对象(对于泛型,这是 JIT 编译时,但它的工作原理相同)。

因此,您不能直接将 Type 对象用作泛型参数,因为它是一个对象,而不是类型引用。

但是请注意,由于 typeof 返回一个 Type 对象,因此可以通过直接使用 typ 来解决这种情况。

  List<double> source = new List<double>();
  source.Add(1);
  Type typ = source.First().GetType();
  var newVal = Convert.ChangeType(source.First(), typ);

关于c# - 使用参数转换数据类型 - ChangeType() 范围问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29259207/

相关文章:

c# - Web API 2 的不区分大小写的路由

c# - 带有 ContinueWith 的 TaskCanceledException

Haskell 集合保证每个操作的最坏情况界限?

java - Streams API::如何从 LIST<Object> 修改自定义对象的变量?

c# - 将数组从可空类型转换为相同类型的不可空类型?

c# - 我们如何从一种表单更改所有其他表单的背景颜色?

c# - 如何设置 ComboBox 的高度?

c# - 如何使用 GAC 和 NGEN 部署 C# 应用程序

c# - 在 AssemblyInitialize 或 ClassInitialize 中检测 TestCategory 的方法?

java - 当实际对象被垃圾回收时,WeakHashMap 中条目中的值如何被垃圾回收?