使用Get/Set和版本开关定义属性的最有效方法是什么?

c#

我正在编写一个程序来从另一个程序读取和写入内存,但是有两个不同的版本,并且内存值在一个版本中具有偏移量,但在第二个版本中没有,因此取决于用户选择的设置(v1 或 v2 ) 我需要确定要读/写的地址。

由于我的代码如下所示,但我觉得这不是很有效,并且在真正不需要时复制相同的代码会使类变得很长。

有没有更有效的方法来做这一切:

public static int Property
{
    get
    {
        switch (Version)
        {
            case Version.v1:
                return Memory.ReadMemory<int>(0xB7CE50 + 0x2680);
            case Version.v2:
                return Memory.ReadMemory<int>(0xB7CE50);
            default:
                return 0;
        }
    }
    set
    {
        switch (Version)
        {
            case Version.v1:
                Memory.WriteMemory<int>(0xB7CE50 + 0x2680, value);
                break;
            case Version.v2:
                Memory.WriteMemory<int>(0xB7CE50, value);
                break;
            default:
                break;
        }
    }
}

并非所有地址都需要这个偏移量,但大多数都需要,所以我也需要考虑到这一点,因此如果 v2,我不能只添加 0x2680 值

回答

解决这个问题的一种显而易见的方法是将关于生活在何处的知识带入一个中心位置。您可能希望扩展 a 的定义Version以包含内存地址(见下文),或者您可能希望将此信息包含在其他某个类中:

public class Version
{
    public int PropertyAddress { get; init; }

    public static Version Version1 { get; } = new()
    {
        PropertyAddress = 0xB7CE50 + 0x2680,
    };

    public static Version Version2 { get; } = new()
    {
        PropertyAddress = 0xB7CE50,
    };

    private Version() { }
}

(我在这里使用了 C# 9 语法——如果您的目标是早期语言版本,请进行调整)。

然后,您可以将您的财产简化为:

public static int Property
{
    get => Memory.ReadMemory<int>(Version.PropertyAddress);
    set => Memory.WriteMemory<int>(Version.PropertyAddress, value);
}

例如,您也可以将它放在一个MemoryAddresses类中(如果您想保留Version为枚举),然后执行以下操作:

private static MemoryAddresses Addresses => Version switch
{
    Version.V1 => MemoryAddresses.V1,
    Version.V2 => MemoryAddresses.V2,
};

public static int Property
{
    get => Memory.ReadMemory<int>(Addresses.PropertyAddress);
    set => Memory.WriteMemory<int>(Addresses.PropertyAddress, value);
}

如果您想利用一个版本中的某些地址是另一个版本中地址的偏移版本这一事实,您可以执行以下操作:

public class Version
{
    public int Offset { get; init; }

    public int Property1Address => 0xB7CE50 + Offset;
    public int Property2Address => 0xB80000 + Offset;
    public int Property3Address { get; init; }

    public static Version Version1 { get; } = new()
    {
        Offset = 0x2680,            // <-- Offset for version 1
        Property3Address = 123456,  // <-- Explicit address for version 1
    };

    public static Version Version2 { get; } = new()
    {
        Offset = 0,                 // <-- No offset for version 2
        Property3Address = 987654,  // <-- Different explicit address for version 2
    };

    private Version() { }
}


以上是使用Get/Set和版本开关定义属性的最有效方法是什么?的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>