简体   繁体   中英

Generic extension method, operators

I would like to make a method that "transforms" one space to another. This is quite a simple thing to template in C++ but in C# I'm not sure which interface/type or how I need to use the "where" clause in order to get the compiler to understand what I want. My C++ function looked like this:

template<class T>
T Transform(T s, T s1, T s2, T d1, T d2)
{
        T result = (s - s1) / (s2 - s1) * (d2 - d1) + d1;       

        return result;
}   

and my first stab at a generic C# version (in extension methods), looks like this:

public static T Transform<T>(T s, T s1, T s2, T d1, T d2)
{
        T result = (s - s1) / (s2 - s1) * (d2 - d1) + d1;       

        return result;
}

Alas C# would like me to be more specific about the types, ie

"error CS0019: Operator '-' cannot be applied to operands of type 'T' and 'T'".

What does C# want me to do?

You cannot directly tell the compiler via a constraint that T implements a certain operator. You can only tell the compiler that T implements some class. If this class overloads the operator, then you can use it.

For example, a class that defines the '-' operator

public class Stuff
{
    public Stuff(int number) {
        Number = number;
    }

    public int Number { get; set; }

    public static Stuff operator -(Stuff a, Stuff b) {
        return new Stuff(a.Number - b.Number);
    }

    //Define the other operators in the same way...
}

Then, in your method, you can do this:

public static T Transform<T>(T s, T s1, T s2, T d1, T d2)
    where T : Stuff
{
    Stuff result = (s - s1) / (s2 - s1) * (d2 - d1) + d1;
    return (T)result;
}

Alternatively, you can just use dynamic , but that will throw an exception if the operator does not exist.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM