我试图作出类型转换它获取一个对象,并对象的类型待铸造的通用方法。

通过使用Convert.ChangeType()我可以做我想做的,但它需要太多的时间在运行时间。是什么力量让一个泛型类像我想要的最好方法。

我的旧代码看起来像;

public static ConvertTo<T>(object data) where T : struct // yes the worst variable name!
{
  // do some controls...

  return Convert.ChangeType(data, typeof(T));
}

编辑: 为了澄清...

有关实施例;我执行我的查询,它返回一个DataRow。还有是类型为小数,我想转换为长列。如果我把这种方法,它需要这么多的时间来施放小数长。

此方法的和T型可能是唯一值类型。我的意思是 “T:结构”

有帮助吗?

解决方案

我仍然怀疑你的性能要求。这里的证据。编译并运行下列程序(释放模式):

using System;
using System.Diagnostics;

class Test
{
    const int Iterations = 100000000;

    static void Main()
    {
        Stopwatch sw = Stopwatch.StartNew();
        decimal d = 1.0m;
        long total = 0;
        for (int i=0; i < Iterations; i++)
        {
            long x = ConvertTo<long>(d);
            total += x;
        }
        sw.Stop();
        Console.WriteLine("Time: {0}ms", sw.ElapsedMilliseconds);
        Console.WriteLine("Total: {0}", total);
    }

    public static T ConvertTo<T>(object data) where T : struct
    {
        return (T) Convert.ChangeType(data, typeof(T));
    }
}

这需要在我的笔记本20秒 - 要执行亿次迭代。很难相信,它需要在您的计算机上8秒执行40次迭代。

在换句话说,我强烈怀疑,这个问题是不是你认为它是。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top