简体   繁体   中英

C# interface to check type T has an operator / A way to check if type T has an operator

interface IMathable
{
    public static IMathable operator +(IMathable l, IMathable r);
    public static IMathable operator -(IMathable l, IMathable r);
}

Is such possible? I have range of mathmatical class. Vector2/3/4/5/6 Matrix3x3/4x4/5x5/6x6 and so on.

They don't have a common class that they drive from. But they all have operators such as + - * /

I want to have a class like.

class MyClass <T> where T : IMathable
{
    T magnitude_required_to_reach_toHere;

    public MyClass (IMathable from, IMathable toHere)
        {
            magnitude_required_to_reach_toHere = from + toHere;
        }
}

Is there a way to achieve this? I was advised to have all my math classes to drive from abstract class but I can't have abstract class for all these mathmatical classes since they are built in, part of library; I can't fix the code.

As far as I know, you cannot define operators on an interface.

But operators are more or less syntactical sugar.

You could define:

interface IMathable {

    IMathable add (IMathable other);
    IMathable sub (IMathable other);

}

In fact an operator is more or less a method, but where the identifier of that method (the + and - ) and where the compiler maintains a symbol table and finds out the appropriate operator itself.


Edit : What you ask is not possible. Especially since an IMathable can't know what the supposed return type should be.

There is however some kind of workaround to solve it by using some functional programming:

class MyClass <T> {

    T magnitude_required_to_reach_toHere;

    public MyClass (T from, T toHere, Func<T,T,T> addfunction) {
            magnitude_required_to_reach_toHere = addFunction(from,toHere);
        }
}

Thus you pass a function as argument that must have the computational knowledge on how to solve the problem. For instance if T is an integer:

 MyClass<int> mc = new MyClass<int>(5,7,(x,y) => x+y);

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