gpt4 book ai didi

c# - 一个对象如何同时为 null 和不为 null?

转载 作者:太空狗 更新时间:2023-10-29 23:13:08 25 4
gpt4 key购买 nike

所以我有这段代码,如果我在 return 语句上打断点,即时窗口会输出以下信息。

try
{
await connection.OpenAsync();
var obj = await cmd.ExecuteScalarAsync();
return obj != null ? Int32.Parse(obj.ToString()) != 1 : false;
}
catch (Exception ex)
{
Log.Error("An error has occurred checking a customer/product authorization.", ex);
return false;
}
finally
{
connection.Close();
}

存储过程这是存储过程的相关部分。 @HasAuthTable 和@IsAuthorized 是bit 类型。

SELECT (CASE WHEN @HasAuthTable = 0 THEN 1 ELSE 0 END) | @IsAuthorized AS IsAuthorized

立即窗口

obj
0

obj == null
false

obj != null
false

obj == 0
error CS0019: Operator '==' cannot be applied to operands of type 'object' and 'int'

obj != 0
error CS0019: Operator '!=' cannot be applied to operands of type 'object' and 'int'

(int)obj == 0
true

(int)obj != 0
false

obj.GetType().FullName
"System.Int32"

obj.Equals(null)
false

!obj.Equals(null)
true

Object.ReferenceEquals(obj, null)
false

!Object.ReferenceEquals(obj, null)
false

我试过重建解决方案没有改变任何东西。我也试过重新启动 Visual Studio。没有运气。这是有意的行为吗?这似乎是一个错误。

改变的存储过程我尝试更改存储过程的输出以匹配以下内容以查看它是否以任何方式影响它。结果基本一样。具有预期动态类型的 object 的静态类型,两者都有值,但对于 obj == nullobj != 仍返回 false

SELECT CAST(((CASE WHEN @HasAuthTable = 0 THEN 1 ELSE 0 END) | @IsAuthorized) AS BIT) AS IsAuthorized

各自的即时窗口

obj
false

obj != null
false

obj == null
false

obj.GetType().FullName
"System.Boolean"

最佳答案

var obj = await cmd.ExecuteScalarAsync(); 正在执行装箱

enter image description here

如果 0 被装箱,则立即窗口显示不正确的值。这一定是立即窗口中的错误。

enter image description here

图片来自Illustrated C# 2012 4th Edition by Daniel Solis .

关于c# - 一个对象如何同时为 null 和不为 null?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38645220/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com