Compiler Error CS0019

运算符“operator”无法应用在“type”和“type”类型的操作数

对不支持二元运算符的数据类型应用该运算符。例如,您不能对字符串使用 || 运算符,不能对 bool 变量使用 +-<> 运算符,并且不能将 ==运算符与 struct类型一起使用(除非该类型显式重载了该运算符)。

如果在处理类类型时遇到此错误,则原因是该类未重载运算符。有关详细信息,请参阅可重载运算符(C# 编程指南)

在下面的示例中,将在两个位置生成 CS0019,原因是 C# 中的 bool 不能转换为 int。将减法运算符应用于字符串时,还会生成 CS0019。请注意,加法运算符 (+) 可与字符串操作数一起使用,因为 String 类会重载该运算符以执行字符串串联。

static void Main()
{
    bool result = true;
    if (result > 0) //CS0019
    {
        // Do something.
    }

    int i = 1;
    // You cannot compare an integer and a boolean value.
    if (i == true) //CS0019
    {
        //Do something...
    }

    // The following use of == causes no error. It is the comparison of
    // an integer and a boolean value that causes the error in the 
    // previous if statement.
    if (result == true)
    {
        //Do something...
    }

    string s = "Just try to subtract me.";
    float f = 100 - s; // CS0019
}

在下面的示例中,必须在 ConditionalAttribute 外指定条件逻辑。只能向 ConditionalAttribute 传递一个预定义符号。

下面的示例生成 CS0019。

// CS0019_a.cs
// compile with: /target:library
using System.Diagnostics;
public class MyClass
{
   [ConditionalAttribute("DEBUG" || "TRACE")]   // CS0019
   public void TestMethod() {}

   // OK
   [ConditionalAttribute("DEBUG"), ConditionalAttribute("TRACE")]
   public void TestMethod2() {}
}

请参阅

运算符(C# 编程指南)

隐式数值转换表(C# 参考)