Can There Be Private Extension Methods?

后端 未结 6 1617
Happy的楠姐
Happy的楠姐 2021-01-07 16:01

Let\'s say I have a need for a simple private helper method, and intuitively in the code it would make sense as an extension method. Is there any way to encapsulate that hel

6条回答
  •  暗喜
    暗喜 (楼主)
    2021-01-07 16:33

    I believe it is the way they implemented the compiling of the Extensions Methods.

    Looking at the IL, it appears that they add some extra attributes to the method.

    .method public hidebysig static int32 GetNext(int32 i) cil managed
    {
        .custom instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor()
        .maxstack 2
        .locals init (
            [0] int32 num)
        L_0000: nop 
        L_0001: ldarg.0 
        L_0002: ldc.i4.1 
        L_0003: add 
        L_0004: dup 
        L_0005: starg.s i
        L_0007: stloc.0 
        L_0008: br.s L_000a
        L_000a: ldloc.0 
        L_000b: ret 
    }
    

    There is probably some very fundamental that we are missing that just doesn't make it work which is why the restriction is in place. Could also just be that they wanted to force coding practices. Unfortunately, it just doesn't work and has to be in top-level static classes.

提交回复
热议问题