是否有可能使用.NET编写只接受数值类型的通用功能? [英] Is it possible to write a generic function in .NET that only accepts numerical types?

查看:114
本文介绍了是否有可能使用.NET编写只接受数值类型的通用功能?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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).

这篇关于是否有可能使用.NET编写只接受数值类型的通用功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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