简体   繁体   English

运算符“ ”不能应用于类型的操作数<int>和空

[英]Operator ' ' cannot be applied to operand of type <int> and null

I have the below method that accepts BuildAppStat object as parameter.我有下面的方法接受BuildAppStat对象作为参数。
However it can be null sometimes.但是有时它可以为空。

So I am calling it like as :所以我称之为:

sourceId: bas.BuildAppStatId ?? null

and getting compile error并得到编译错误

operator ' ' cannot be applied to operand of type <int> and null .运算符“ ”不能应用于<int>null类型的操作数。

How can I fix this?我怎样才能解决这个问题?

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;
}

You can only use the null-coalescing operator with a first operand which is a nullable type (either a nullable value type, or any reference type).您只能将空合并运算符与第一个操作数一起使用,该操作数是可空类型(可为空值类型或任何引用类型)。 It sounds like bas.BuildAppStatId is just an int , which means you can't use the null-coalescing operator with it.听起来bas.BuildAppStatId只是一个int ,这意味着您不能将空合并运算符与它一起使用。

If you were trying to guard against bas itself being null, you want:如果您试图防止bas本身为空,您需要:

sourceId: bas == null ? (int?) null : bas.BuildAppStatId,

From ?? Operator (C# Reference)?? Operator (C# Reference) ?? Operator (C# Reference)

The ?? ?? operator is called the null-coalescing operator and is used to define a default value for nullable value types or reference types .运算符称为空合并运算符,用于为可空值类型引用类型定义默认值。

Since your bas.BuildAppStatId is an int , you can't use ??由于您的bas.BuildAppStatIdint ,您不能使用?? in here.在这里。

BuildAppStatId should be declared as a nullable int. BuildAppStatId 应声明为可为空的 int。

int?

then if you have trouble with "?? null", use either然后,如果您对“?? null”有疑问,请使用

... ?? null as int?

or要么

... ?? default(int?)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM