报错:Operator '??'无法应用于'int'类型操作数,求解决方案
Hey Ceci, let's break down this ?? operator error you're hitting—super common once you clarify how the operator actually works!
First, why you're seeing this error
The ?? (null-coalescing) operator only makes sense when the left operand is a nullable type (like int?) or a reference type—its whole job is to check if the left value is null and fall back to the right value if it is. When both operands are non-nullable ints, the compiler throws this error because a non-nullable int can never be null—using ?? here is redundant at best, and invalid at worst.
You mentioned changing int? to non-nullable int didn't fix the issue—chances are you mixed up which variable needs to be nullable. The problem isn't the type of your fee variable, but the type of the value you're using on the left side of the ?? operator.
Fixes to try
Let's walk through the two most common scenarios:
1. You're dealing with a value that might actually be null (e.g., database results, optional method returns)
If your use case is handling a value that could be null, make sure the left operand is declared as a nullable int?, then use ?? to fall back to a default non-nullable value. For example:
// This could come from a method that returns int? (nullable int) int? nullableFee = GetFeeFromDatabase(); // Use ?? to safely convert to non-nullable int with a default int fee = nullableFee ?? 0;
2. You're trying to handle a non-null condition (like a default for zero or another value)
If both values are guaranteed to be non-null, you don't need ?? at all. Use the ternary operator ?: instead, which works with any boolean condition. For example, if you want to use a default when the value is zero:
int rawFee = GetNonNullableFee(); int fee = rawFee != 0 ? rawFee : 5; // Fallback to 5 if rawFee is 0
Quick example of what not to do (your error case)
This will throw the exact error you're seeing, because both operands are non-nullable ints:
int a = 3; int b = 7; int fee = a ?? b; // ❌ Error: ?? can't be applied to int and int
Double-check your code
Take a look at the line with the ?? operator—confirm which side is the potentially null value. If you changed fee to non-nullable but the value on the left of ?? is still a non-nullable int, that's why the error persists. The left operand needs to be int? for ?? to be valid.
Hope this clears things up and gets your code running again!
内容的提问来源于stack exchange,提问作者ceci

