简体   繁体   English

用于检查类型T的C#接口具有运算符/一种检查类型T是否具有运算符的方法

[英]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. Vector2 / 3/4/5/6 Matrix3x3 / 4x4 / 5x5 / 6x6等。

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. 特别是因为IMathable无法知道假定的返回类型应该是什么。

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: 例如,如果T是整数:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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