在 C# 中使用 F__AnonymousType 时出错

Errors using F__AnonymousType in C#

我花了几个小时试图解决与 f__AnonymousType 相关的编译问题。似乎有很多关于需要指令的表达式的错误,但不确定具体要做什么。

public static void ChangeSerialNumber(char volume, uint newSerial)
{
    var source = new <>f__AnonymousType0<string, int, int>[]
    {
        new
        {
            Name = "FAT32",
            NameOffs = 82,
            SerialOffs = 67
        },
        new
        {
            Name = "FAT",
            NameOffs = 54,
            SerialOffs = 39
        },
        new
        {
            Name = "NTFS",
            NameOffs = 3,
            SerialOffs = 72
        }
    };

    using (Helpers.Disk disk = new Helpers.Disk(volume))
    {
        byte[] sector = new byte[512];
        disk.ReadSector(0U, sector);
        var <>f__AnonymousType = source.FirstOrDefault(f => Helpers.Strncmp(f.Name, sector, f.NameOffs));
        if (<>f__AnonymousType == null)
        {
            throw new NotSupportedException("This file system is not supported");
        }

        uint num = newSerial;
        int i = 0;
        while (i < 4)
        {
            sector[<>f__AnonymousType.SerialOffs + i] = (byte)(num & 255U);
            i++;
            num >>= 8;
        }
        disk.WriteSector(0U, sector);
    }
}

这用于 USB 记忆棒翻新,以便作为软件的一部分进行安全擦除,我们想更改驱动器的序列号(实际上是欺骗它们)以防退款,我们可以匹配驱动器他们 return 以确保它是我们发出的那个。

关于匿名类型的要点是,您不必给它们命名,编译器会为您命名。

<>f__AnonymousType0 在用户代码中不是有效名称,但看起来像是编译器生成的名称。你不能使用它。

只需使用 anonymous syntax :

public static void ChangeSerialNumber(char volume, uint newSerial)
{
    var sources = new[]
    {
        new
        {
            Name = "FAT32",
            NameOffs = 82,
            SerialOffs = 67
        },
        new
        {
            Name = "FAT",
            NameOffs = 54,
            SerialOffs = 39
        },
        new
        {
            Name = "NTFS",
            NameOffs = 3,
            SerialOffs = 72
        }
    };

    using (Helpers.Disk disk = new Helpers.Disk(volume))
    {
        byte[] sector = new byte[512];
        disk.ReadSector(0U, sector);

        var source = sources.FirstOrDefault(f => Helpers.Strncmp(f.Name, sector, f.NameOffs));
        if (source == null)
        {
            throw new NotSupportedException("This file system is not supported");
        }

        var num = newSerial;
        var i = 0;
        while (i < 4)
        {
            sector[source.SerialOffs + i] = (byte) (num & 255U);
            i++;
            num >>= 8;
        }

        disk.WriteSector(0U, sector);
    }
}