开发者

Generics and "One of the parameters of a binary operator must be the containing type" Error

When declaring a binary operator, at least one of the operand types must be the containing type. This sounds a good design decision in general. However, I didn't expect the following code to cause this error:

public class Exp<T>
{
    public static Ex开发者_开发百科p<int> operator +(Exp<int> first, Exp<int> second)
    {
        return null;
    }
}

What is the problem with this operator? Why this case falls into operator overloading restrictions of c#? is it dangerous to allow this kind of declaration?


Because the containing type is Exp<T>, not Exp<int>. What you are trying to do here is specialization a la C++, which is not possible in C#.


You are in a class of type Exp<T>, and neither of the parameters in the operator are Exp<T>, they're both Exp<int>.

Read this article for the suggested way around this.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜