Could you hire me? Contact me if you like what I’ve done in this article and think I can create value for your company with my skills.

February 9, 2015 / by Zsolt Soczó

.NET fejtörő 5.

Mi a gond az alábbi kóddal?

class Teaser4
{
    int Item = 0;

    public int this[params int[] arr]
    {
        get
        {
            return Item;
        }
    }
}

Could you hire me? Contact me if you like what I’ve done in this article and think I can create value for your company with my skills.

LEAVE A COMMENT

3 COMMENTS

  • Haraszti Gábor February 9, 2015

    Szerintem találtál egy bugot. Ha átnevezem Item2-re a privát adattagot, akkor rögtön látszik az IL-ből, hogy az indexer get_Item-é lényegül át. Valószínűleg így ütközhet a privát adattaggal, aminél ugye nem generálódna getter, mint a property-k esetében, de ez a fordító egy bugja lehet.

    IL_0001: newobj UserQuery+Teaser4..ctor
    IL_0006: stloc.0 // t
    IL_0007: ldloc.0 // t
    IL_0008: ldc.i4.2
    IL_0009: newarr System.Int32
    IL_000E: stloc.1 // CS$0$0000
    IL_000F: ldloc.1 // CS$0$0000
    IL_0010: ldc.i4.1
    IL_0011: ldc.i4.1
    IL_0012: stelem.i4
    IL_0013: ldloc.1 // CS$0$0000
    IL_0014: callvirt UserQuery+Teaser4.get_Item
    IL_0019: call LINQPad.Extensions.Dump

    Teaser4.get_Item:
    IL_0000: nop
    IL_0001: ldarg.0
    IL_0002: ldfld UserQuery+Teaser4.Item2
    IL_0007: stloc.0 // CS$1$0000
    IL_0008: br.s IL_000A
    IL_000A: ldloc.0 // CS$1$0000
    IL_000B: ret

    Teaser4..ctor:
    IL_0000: ldarg.0
    IL_0001: ldc.i4.0
    IL_0002: stfld UserQuery+Teaser4.Item2
    IL_0007: ldarg.0
    IL_0008: call System.Object..ctor
    IL_000D: nop
    IL_000E: ret

  • Molnár Csaba February 10, 2015

    C#-ban az idexer egy indexelt property, aminek alapértelmezetten Item a neve. Ezért fordítási hibát kapunk ennél a kódnál, hogy már van definíció az Item-re. Ezt kétféle módon tudjuk elkerülni:
    1. Az Item property-t átnevezzük valami másra.
    2. Használjuk az indexeren az IndexerNameAttribute-ot, amivel megadhatjuk, hogy milyen néven jöjjön létre az indexer (ne Item néven).