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

C# 是否可以从自己的getter中的数组类型属性获取索引,c#,properties,getter,C#,Properties,Getter,如果我有一个数组属性 private byte[] myProperty; public byte[] MyProperty { get { return myProperty; } set { myProperty= value; } } 我可以称之为 MyProperty[3] 我想在getter中得到索引值3。 可以像这样从自己的getter中的数组类型属性获取索引吗 public byte[] MyProperty[int index] { get

如果我有一个数组属性

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);
    }
}
public byte[] MyPropertyMethod(int index) => MyMethod(index);
没有像这样使用自己的类型,也没有像这样将属性更改为方法

public byte[] MyProperty[int index]
{
    get 
    {
        return MyMethod(index);
    }
}
public byte[] MyPropertyMethod(int index) => MyMethod(index);

有你描述的限制

不使用自己的类型,也不将属性更改为方法

这是不可能的(使用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代码修补。您需要使用第三方工具甚至手动“破解”已编译的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

你不需要这个。当属性是数组时,它仍然具有索引访问权限。你为什么要重新发明它?你为什么要这么做?您只需调用
instance.MyProperty[3]
进行比较,您需要在Delphi中查找类似索引器属性的内容,对吗?@HimBromBeere:数组的索引器具有读写访问权限,并直接从数组读取/写入(很明显)。如果您使用的是基于索引的getter,则不再返回字节数组,而是返回单个字节。您可以轻松地在自己的类型上实现一个索引器,该索引器将反映数组的索引器。@O.R.Mapper是的,它可能是类似的