是否有可能使用.NET编写只接受数值类型的通用功能?有可能、数值、类型、功能

2023-09-05 02:45:54 作者:不离不弃只是童年无忌

假设我想写这样一个函数如下(像往常一样,一个简单的例子,用于说明目的):

Suppose I want to write a function like the following (as usual, a trivial example for illustrative purposes):

Public Function calcSqSum(Of T)(ByVal list As IEnumerable(Of T)) As T
    Dim sumSq As T

    For Each item As T In list
        sumSq += (item * item)
    Next

    Return sumSq
End Function

正如你可能已经猜到,此功能会导致一个错误,因为一个通用对象不能保证实施+运营商。据我所知,不过,任何数值类型(整数,双数,小数等)会的。

As you can probably guess, this function causes an error because a generic object is not guaranteed to implement the + operator. As far as I know, though, any numerical type (Integer, Double, Decimal, etc.) will.

有没有办法写一个(准)通用功能,可以接受任何的数字类型,而无需显式重载函数每个这种类型的自己呢?

Is there a way to write a (quasi-)generic function that can accept any numerical type, without having to explicitly overload the function for every such type yourself?

另外,我想同样可以接受的解决办法是,以某种方式检查一个类型实现了+操作​​符(或功能与数值类型一般关联并用于任何运营商)。

Alternatively, I suppose an equally acceptable solution would be to somehow check if a type implements the '+' operator (or any operator generally associated with numerical types and used by the function).

推荐答案

没有,因为没有具体的共同界面,所有这些工具。从本质上说,有一个在框架数字类型没有真正的概念。除非你包装在自定义的类,有你的方法,只接受你的类型(这是不是一个真正的直接回答你的问题,只是一种变通方法)。

No, since there's no specific common interface that all of them implement. In essence, there's no real notion of "numerical types" in the framework. Unless you wrap them in self-defined classes and have your method accept only your types (which is not really a direct answer to your question, just a workaround).

 
精彩推荐