[英]Attempting to assign null to nullable int results in “There is no implicit conversion between 'int' and 'null'” error
public List<Tuple<int, int, int, string, int, int, Tuple<bool, bool, int?>>>
GetValues(int someId, int someOtherlId)
{
var t = new List<Tuple<int, int, int, string, int, int, Tuple<bool, bool, int?>>>();
using (var context = new Entities(ConnString))
{
var pc = context.SomeTable.Where(c => c.SomeId == someId &&
c.SomeOtherId == someOtherId).OrderBy(c => c.Id).ToList();
t.AddRange(pc.Select(cols => new Tuple<int, int, int, string, int, int, Tuple<bool, bool, int?>>
(cols.Id, cols.someId, cols.someOtherId, cols.ColumnName, cols.MinDataLength,
cols.MaxDataLength, new Tuple<bool, bool, int?>(cols.Required, cols.Eav.HasValue && cols.Eav.Value,
cols.AttribId.HasValue ? cols.AttribId.Value : null))));
}
return t;
}
}
Can't figure out why this code won't compile and generates "There is no implicit conversion between 'int' and 'null'" error. 无法弄清楚为什么此代码无法编译并生成“'int'和'null'之间没有隐式转换”错误。
In that second Tuple the int? 在第二个元组int吗? is consistently marked as nullable so why is it being detected as a normal int by the compiler in t.AddRange
which generates "Type of conditional expression cannot be determined because there is no implicit conversion between 'int' and ''" error at cols.AttribId.HasValue ? cols.AttribId.Value : null
始终标记为可空,因此为什么编译器会在t.AddRange
其检测为正常int,该生成器生成“无法确定条件表达式的类型,因为cols.AttribId.HasValue ? cols.AttribId.Value : null
'int'和''“错误之间没有隐式转换cols.AttribId.HasValue ? cols.AttribId.Value : null
cols.AttribId.HasValue ? cols.AttribId.Value : null
. cols.AttribId.HasValue ? cols.AttribId.Value : null
。
Any ideas? 有任何想法吗?
Try this: 尝试这个:
cols.AttribId.HasValue ? (int?)cols.AttribId.Value : null
What's happening is that the C# ternary there has to exist implicit conversion between both values. 发生的情况是,C#三元数必须在两个值之间存在隐式转换。 When you write: 当你写:
cols.AttribId.HasValue ? cols.AttribId.Value : null
cols.AttribId.Value
is an int
which cannot be converted to null
. cols.AttribId.Value
是一个不能转换为null
的int
。 An int?
一个int?
however can be converted to null
. 但是可以转换为null
。
If you're trying to add an int?
如果您要添加一个int?
to a tuple that already accepts int?
到已经接受int?
的元组int?
why not just add it directly to your tuple—ie replace: 为什么不直接将其添加到您的元组,即替换:
new Tuple<bool, bool, int?>(..., cols.AttribId.HasValue ? cols.AttribId.Value : null)
With 同
new Tuple<bool, bool, int?>(..., cols.AttribId)
Or to a little bit cleaner, take advantage of type inference with Tuple.Create
: 或者稍微干净一点,利用Tuple.Create
的类型推断优势:
Tuple.Create(..., cols.AttribId)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.