gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 23:40:23 25 4
gpt4 key购买 nike

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

这样做的原因是我有一个扩展方法,它将对 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com