c# 对象 obj 的值为 {}.什么是“{}"? [英] c# Object obj's value is {}. What is "{}"?
问题描述
我正在使用一些运行 sql 查询的旧代码作为参考.
I'm using some old code that runs a sql query as a reference.
在某些时候,它会变成这样:
At some point, it gets to something like:
sqlDataAdapter.Fill(dataSet);
DataRow dataRow = dataSet.Tables[0].Rows[0];
Object obj = dataRow[fieldName];
旧代码:
string output;
if (!string.IsNullOrEmpty(obj.ToString())) { output = obj.ToString(); }
else { output = "Not Available"; }
我将它们更改为:
output = obj as string ?? "Not Available"
但有时,它坏了.正如我怀疑的那样,当条目是 int
时,它正在发生中断.在这些情况下转换为 int
解决了这个问题.
But sometimes, it broke. As I suspected, it was happening breaking when the entry was an int
. Casting as an int
in those cases solved that problem.
然后当obj[fieldName]
类型为int 的没有 条目时出现了另一个问题.当我逐步调试调试器时,我惊讶地发现 obj
不是 null
.在 VS 中,鼠标悬停显示它有一个值 {}
.
Then another problem arose when there was no entry for obj[fieldName]
of type int. When I stepped through the debugger, I was surprised to find that obj
wasn't null
. In VS, mousing over revealed it had a value {}
.
{}
到底是什么?我如何对其进行布尔测试?
What the heck is {}
? How do I make a boolean test of it?
(在旧代码中,它出现 .ToString()
在这种情况下返回 ""
并按预期工作.)
(In the old code, it appears .ToString()
returns ""
in this case and works as expected.)
推荐答案
{
和 }
是左括号和右括号,是对象开始和结束的符号.因此,一个没有特殊属性的空对象被简写为 {}
.调试器使用这种表示法来帮助您直观地区分空对象、空字符串和 null.
{
and }
are opening and closing braces and symbolic of the start and finish of an object. Hence an empty object with no special properties is depicted in shorthand as {}
. The debugger uses this notation to help you visually distinguish between an empty object, an empty string and null.
如果您将鼠标悬停在 obj[fieldName]
上并且没有 fieldName
的条目,则调试器不会关心它,它会显示 <代码>对象代码>.您必须使用立即窗口或手表/快速手表.调试器只会看到您将鼠标悬停在 obj 上,并假设您指的是数组本身,而不是指定索引处的数组内容.
If you hover over obj[fieldName]
and there is no entry for fieldName
, the debugger won't care about that, it'll show the value of obj
. You'll have to use the immediate window or a watch/quickwatch. The debugger will only see you hovering over obj and assume you're referring to the array itself, not the contents of the array at the specified index.
这篇关于c# 对象 obj 的值为 {}.什么是“{}"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!