![](/img/trans.png)
[英]Operator '&&' cannot be applied to operand of type 'bool' and 'int'
[英]Operator ' ' cannot be applied to operand of type <int> and null
我有下面的方法接受BuildAppStat
对象作为参数。
但是有时它可以为空。
所以我称之为:
sourceId: bas.BuildAppStatId ?? null
并得到编译错误
运算符“ ”不能应用于
<int>
和null
类型的操作数。
我怎样才能解决这个问题?
public PageBuildVrsn EditPageBuildVrsn(string caption, string nameInUse, string description, BuildAppStat bas = null, int pageBuildVrsnTypeId = 1)
{
PageBuildVrsn pbv = Create(pageBuildVrsnTypeId, caption, nameInUse, description);
pbv.ParentBuildAppStats = new List<BuildAppStat>();
pbv.ParentBuildAppStats.Add(
BasFactory.Create(
DateTimeOffset.Now,
true,
sourceId: bas.BuildAppStatId ?? null
)
);
return pbv;
}
您只能将空合并运算符与第一个操作数一起使用,该操作数是可空类型(可为空值类型或任何引用类型)。 听起来bas.BuildAppStatId
只是一个int
,这意味着您不能将空合并运算符与它一起使用。
如果您试图防止bas
本身为空,您需要:
sourceId: bas == null ? (int?) null : bas.BuildAppStatId,
从?? Operator (C# Reference)
?? Operator (C# Reference)
?? 运算符称为空合并运算符,用于为可空值类型或引用类型定义默认值。
由于您的bas.BuildAppStatId
是int
,您不能使用??
在这里。
BuildAppStatId 应声明为可为空的 int。
int?
然后,如果您对“?? null”有疑问,请使用
... ?? null as int?
要么
... ?? default(int?)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.