我有类似于以下代码的内容,它使用反射查找成员:
private static object GetPrivateFieldValue(object target, string fieldName)
{
var targetType = target.GetType();
var targetField = targetType.GetField(fieldName, BindingFlags.NonPublic | BindingFlags.Instance);
if (targetField == null)
{
throw new NullReferenceException(string.Format("{0}.{1} is null", targetType.Name, fieldName));
}
var fieldValue = targetField.GetValue(target);
return fieldValue;
}
在一个特殊情况下,我按如下方式使用它:
var values = (object[]) GetPrivateFieldValue(currentItem, "_values");
foreach (var fieldName in recordsReaderCacheEntry.FieldNames)
{
var valueIndex = Array.IndexOf(recordsReaderCacheEntry.FieldNames, fieldName);
var value = values[valueIndex];
currentRecordDictionary.Add(fieldName, value);
}
这在某种程度上工作得很好,如果原始对象中的某个值为空(在值数组中表示为 {}
),它就会失败。
我希望能够检查 value 是否等于 {}
,因此理想情况下我可以将其替换为 null。
但是,这不能编译:
if (value == {})
类似地,下面的也不会:
if (value == object) //obviously
if (value == new {}) //obviously
if (value == new object{}) //i hoped it might work
if (value == null) //this never matches as strictly speaking its not null
编辑
为问题添加了关键的上下文更改细节...抱歉,大家。
最佳答案
编辑:更新问题:
看起来您正在尝试将 value
字段与 DBNull
进行比较,在当前代码中您可以执行以下操作:
var value = values[valueIndex];
if(value is DBNull)
{
value = null;
}
(上一个答案)
如果你这样做:
var values = (object[]) GetPrivateFieldValue(currentItem, "_values");
这意味着您将返回一个数组(可能是空数组)来检查空数组使用 IEnumerable.Any
像:
if(!values.Any())
{
//empty array found
values = null; //set it to null
}
您还可以比较返回数组的Length
,另外最好使用as
运算符进行转换,例如:
var values = GetPrivateFieldValue(currentItem, "_values") as object[];
if(values != null && values.Length == 0)
{
//Empty found
values = null;
}
关于c# - 检查变量时,{} 意味着什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29653963/