【问题标题】:Operator cannot be applied to operands of type 'int' and 'int' [duplicate]运算符不能应用于“int”和“int”类型的操作数[重复]
【发布时间】:2018-08-13 14:17:09
【问题描述】:

下面的代码工作正常,直到发生了一些事情,现在它返回了这个错误消息: 运算符'??'不能应用于“int”和“int”类型的操作数

这是我之前的代码,但现在有什么东西导致了这个错误。

var Amount = (from x in db.Users where x.userID == ID select (x.fee)).Sum() ?? 0;

'fee'定义为

public int? fee { get; set; } //and tried this too

public Nullable<int> fee { get; set; }

据我了解“??”不能对不可为空的类型调用运算符。

使不可为空或删除“?”从'int?'不做任何事情。

有什么建议吗?谢谢!

塞西

【问题讨论】:

  • C#,运算符 ??被称为空合并运算符来检查给定值是否为空,如果为空,则后面的值??将分配给该值。
  • 如果您使用var Amount = (from x in db.Users where x.userID == ID select (x.fee)).Sum()AmountType 是什么?
  • Nullable 和 int?是严格等价的,这不应该是问题。我无法重现您的编译错误。你能创建一个minimal reproducible example 吗?来编译并足以重现问题的代码,并且尽可能短。

标签: c# linq


【解决方案1】:

您根本不需要使用?? 0。 这将导致:

var Amount = (from x in db.Users where x.userID == ID select (x.fee)).Sum();

例子:

http://rextester.com/UVLX36130

LINQ Sum 函数已经接受可为空的类型。它忽略 null 值(或者在这里将它们视为默认值 0,这是等效的)。

此外,它将返回与您求和的相同的可空类型,在这种情况下为int?


我不太明白您是如何使用提供的代码得到错误的,因为这些不会导致任何错误:

int?[] test = {1,2,3, null};

var sum = (from x in test select x).Sum(); // no error here

Console.WriteLine(sum);

var sum2 = (from x in test select x).Sum() ?? 0; // neither there is an error here

Console.WriteLine(sum2);

但是,这不会编译:

int sum3 = (from x in test select x).Sum(); // compilation error

出现此错误:

不能隐式转换类型“int?”到'int'。存在显式转换(您是否缺少演员表?)

这与您的错误相同。

您能否提供更多有关您使用的 C# 版本的信息?

你能仔细检查一下编译错误确实在这一行吗?

或者更好的是,给出一个展示问题的可编译示例?


关于 Sum() 的文档:https://msdn.microsoft.com/en-us/library/bb156065(v=vs.110).aspx

【讨论】:

  • 删除“?? 0”有效。谢谢!
猜你喜欢
  • 1970-01-01
  • 2020-04-18
  • 2018-10-12
  • 2017-09-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多