为什么我的通用扩展方法表示无法转换从T到.....或....至T [英] Why my Generic Extension Method says cannot convert from T to ..... or .... to T

查看:147
本文介绍了为什么我的通用扩展方法表示无法转换从T到.....或....至T的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

另外我的问题

中的任何百分比功能净

在LINQ中的每个元素的百分比

我想创建在.net 4.0通用扩展方法将生成的列表项到列表的总和的百分比。这份名单将只有数字类型的。

i want to create a generic extension method in .Net 4.0 which will generate percentage of the list items to the sum of the list. This list will be of Numeric types only.

我的code是

public static T Percentage<T>(this T array) where T: ? // What should come in place of ? 
{
  double[] darray = (double[])T; // Error convert type 'T' to 'double[]'

  darray = darray.Select(x=> x * 100 / darray.Sum()).ToArray();

  return darray; // Error convert type 'double[]' to 'T'
}

我想这样称呼它

I want to call it like

double[] MD = {8.0,21.0,25.0,13.0,26.0,37.0,37.0,33.0,71.0,9.0};

MD = MD.Percentage().ToArray(); 

我究竟做错了;

What am i doing wrong;

推荐答案

您不能约束类型的数字的价值观。它是该框架的限制的几分

You cannot constrain types by "numeric" values. It is somewhat of a limitation of the framework.

您最好的最好的就是要做到这一点:

Your best best is to do this:

public static IEnumerable<double> Percentage(this IEnumerable<int> values)
{
    var sum = values.Sum();
    return values.Select(v => (double)v / (double)sum).ToArray();
}

public static IEnumerable<double> Percentage(this IEnumerable<long> values)
{
    var sum = values.Sum();
    return values.Select(v => (double)v / (double)sum).ToArray();
}

public static IEnumerable<double> Percentage(this IEnumerable<double> values)
{
    var sum = values.Sum();
    return values.Select(v => v / sum).ToArray();
}

从本质上讲,你需要产生过载为要支持的每个类型。

Essentially you need to produce an overload for each type you want to support.

这篇关于为什么我的通用扩展方法表示无法转换从T到.....或....至T的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆