是否可以从自己的 getter 中的数组类型 属性 获取索引

Is it possible to get index from array type property inside own getter

如果我有一个数组属性

private byte[] myProperty;

public byte[] MyProperty
{
    get { return myProperty; }
    set { myProperty= value; }
}

我可以叫它

MyProperty[3]

我想在 getter 中获取索引值 3。 是否可以像这样

从自己的getter中的数组类型属性获取索引
public byte[] MyProperty[int index]
{
    get 
    {
        return MyMethod(index);
    }
}

不使用您自己的类型 question 并且不将 属性 更改为这样的方法

public byte[] MyPropertyMethod(int index) => MyMethod(index);

根据您描述的限制

without using your own type and without changing property to method

这是不可能的(使用 C# 语言功能)。

C# 语句

byte i = MyProperty[3];

编译成如下IL:

IL_001f: ldloc.0
IL_0020: callvirt instance uint8[] ConsoleApp1.Cls::get_MyProperty()
IL_0025: ldc.i4.3
IL_0026: ldelem.u1

您看到对 属性 getter get_MyProperty 的调用(在偏移量 IL_0020 处)甚至在项目索引已知之前发生。只有在偏移 IL_0025 处,代码才知道需要从数组中加载索引为 3 的数组元素。那时,getter 方法已经返回,所以你没有机会在方法内部的任何地方获取该索引值。

您唯一的选择是低级 IL 代码修补。您将需要使用第三方工具甚至手动 "hack" 编译的 IL 代码,但强烈建议不要同时使用这两种工具。

您需要将对 getter 方法的调用替换为直接调用您的 MyMethod:

IL_001f: ldloc.0   // unchanged
                   // method call at IL_0020 removed
         ldc.i4.3  // instead, we first copy the index value from what was previously at IL_0025...
         callvirt instance uint8[] ConsoleApp1.Cls::MyMethod(int32) // ...and then call our own method
         ldc.i4.3  // the rest is unchanged
         ldelem.u1