![](/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.