Is it possible to write a generic function in .NET that accepts only numeric types?

Suppose I want to write a function similar to 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 raises an error because the universal object is not guaranteed to implement the + operator. However, as far as I know, any numeric type (integer, double, decimal, etc.) will be.

Is there a way to write a (quasi) generic function that can take any number type without having to explicitly overload the function for each such type independently?

Alternatively, I believe that an equally acceptable solution would be to somehow check if the type implements the + operator (or any operator that is usually associated with numeric types and used by the function).

+3
source share
4 answers

No, because there is no single common interface that they all implement. In fact, there is no real concept of "numerical types" in the framework. If you don't wrap them in self-defined classes and let your method accept only your types (which is not really a direct answer to your question, just a workaround).

+8
source

Sorry, you cannot if you have not created your own class of numbers.

public static T Add<T> (T x, T y) where T: MyNumberClass
{ 
// your add code
...
}

, .NET .

+1

-, :

        static T Add<T>(T a, T b)
    {
        // declare the parameters
        ParameterExpression paramA = Expression.Parameter(typeof(T), "a"),
            paramB = Expression.Parameter(typeof(T), "b");
        // add the parameters together
        BinaryExpression body = Expression.Add(paramA, paramB);
        // compile it
        Func<T, T, T> add = Expression.Lambda<Func<T, T, T>>(body, paramA, paramB).Compile();
        // call it
        return add(a, b);
    }

, ( ).

+1

. , :

Public Function calcSqSum(ByVal list As IEnumerable(Of Integer)) As Integer
    Dim sumSq As Integer
    For Each item As Integer In list
        sumSq += (item * item)
    Next
    Return sumSq
End Function

Public Function calcSqSum(ByVal list As IEnumerable(Of Double)) As Double
    Dim sumSq As Double
    For Each item As Double In list
        sumSq += (item * item)
    Next
    Return sumSq
End Function

etc

, , :

Private Function calcSqSum1(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

Public Function calcSqSum(ByVal list As IEnumerable(Of Integer)) As Integer
    Return calcSqSum1(list)
End Function

Public Function calcSqSum(ByVal list As IEnumerable(Of Double)) As Double
    Return calcSqSum1(list)
End Function

etc

, , .

+1

Source: https://habr.com/ru/post/1709772/


All Articles