检查结构的默认值

我的DefaultValue()函数有问题。 它总是返回false ,表示结构不是默认值。

为什么这不起作用?

 [StructLayout(LayoutKind.Sequential)] private struct ArrayItem { public long SrcSize; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 250)] public string SrcFile; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 250)] public string DestFile; } [StructLayout(LayoutKind.Sequential)] private struct MyInfo { public int Count; public int AppOne; public int AppTwo; [MarshalAs(UnmanagedType.ByValArray, SizeConst = 100, ArraySubType = UnmanagedType.Struct)] public ArrayItem[] Files; } private bool DefaultValue(T structure) { if (EqualityComparer.Default.Equals(structure, default(T))) return true; else return false; } //Success returns 'Value Changed' as expected MyInfo fileInfoOne = new MyInfo(); fileInfoOne.Count = 3; fileInfoOne.Files = new ArrayItem[100]; fileInfoOne.Files[0].SrcSize = 100; Debug.Write("fileInfoOne: "); if (DefaultValue(fileInfoOne.Files[0])) Debug.WriteLine("Default Value."); else Debug.WriteLine("Value Changed."); //Fails but has all the default settings, should return 'Default Value' MyInfo fileInfoTwo = new MyInfo(); fileInfoTwo.Files = new ArrayItem[100]; fileInfoTwo.Files[0].SrcSize = 0; fileInfoTwo.Files[0].SrcFile = ""; fileInfoTwo.Files[0].DestFile = ""; Debug.Write("fileInfoTwo: "); if (DefaultValue(fileInfoTwo.Files[0])) Debug.WriteLine("Default Value."); else Debug.WriteLine("Value Changed."); 

不用担心,你的DefaultValue()函数很好:)

但是在调用它时,请确保不使用空数组/字符串对象初始化测试struct成员。 default表示值类型为0 (零),引用类型为null 。 .NET Framework ArrayString是引用类型,因此如果它们不为null ,则该函数将它们报告为非默认值。

希望这也可以帮助其他人……我已经为我的情况想出了一个解决方案。 在我的情况下(处理内存映射)我将空值传递给内存映射,并且该null值最终被读取为空字符串(“”)。 因此,我最终想出了这个函数来检查(帐户)空字符串。 这只适用于我,因为我知道如果我的字符串是空白的,它们无论如何都是无效的,所以它们也可能是空的)。

 private bool NoFile(T structure) { bool valueIsDefault = true; foreach (FieldInfo f in typeof(T).GetFields()) { object defaultVal = f.GetValue(default(T)); object structVal = f.GetValue(structure); if (structVal.GetType() == typeof(string) && (string)structVal == "") structVal = null; if (!object.Equals(structVal, defaultVal)) { valueIsDefault = false; break; } } return valueIsDefault; }