且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

检查结构的默认值

更新时间:2023-11-26 19:03:46

不用担心,你的默认值()功能就好了:)



但是,当你调用它,确保你不会初始化测试结构成员空数组/字符串对象。 默认办法 0 (零)值类型和对于引用类型。 .NET框架阵列字符串是引用类型,所以,如果他们不是,该函数将其报告为非默认值。


There is something wrong in my DefaultValue() function. It ALWAYS returns false, representing that the the structure is NOT the default value.

Why would this not work?

[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>(T structure)
{
    if (EqualityComparer<T>.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.");

No worry, your DefaultValue() function is just fine :)

But when you calling it, make sure you don't initialize the test struct members with empty array/string objects. default means 0(zero) for value types and null for reference types. NET Framework Arrays and Strings are reference types, so if they are not null, the function will report them as non default.