本文介绍了泛型和“二进制运算符的参数之一必须是包含类型".错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在声明二进制运算符时,至少一种操作数类型必须是包含类型.一般来说,这听起来是一个不错的设计决定.但是,我没想到以下代码会导致此错误:

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 Exp<int> operator +(Exp<int> first, Exp<int> second)
    {
        return null;
    }
}

此运算符有什么问题?为什么这种情况属于c#的运算符重载限制?允许这种声明有危险吗?

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?

推荐答案

因为包含的类型是Exp<T>,而不是Exp<int>.您要在此处执行的是专业化 la C ++,这在C#中是不可能的.

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#.

这篇关于泛型和“二进制运算符的参数之一必须是包含类型".错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-30 08:28