简体   繁体   中英

How to decompile a specific method generating the same code when decompiled via DecompileTypeAsString

NOOB with ILSPY

I'm trying to decompile a method via ILSpy. When I use the following, I get the code re-generated that is pretty close to what was typed in the original C#

decompiler.DecompileTypeAsString(new FullTypeName($@"{MyFullTypeName}"));

The generated code looks something like follows.

public async Task<IReadOnlyList> FuncName(parameterList)
{
//Actual code body
}

Whereas when I use the following snippet,

string functionName = "ReflectionNamed__5";
var name = new FullTypeName(functionName);
ITypeDefinition typeInfo = decompiler.TypeSystem.MainModule.Compilation.FindType(name).GetDefinition();
if (typeInfo.Methods.First().HasBody)
{
    var tokenOfFirstMethod = typeInfo.Methods.First().MetadataToken;
    var methodCodeString = decompiler.DecompileAsString(tokenOfFirstMethod);
    Console.WriteLine(methodCodeString);
}

The code generated is as following:

//Using statements

    private void MoveNext()
    {
        int num = <>1__state;
        IReadOnlyList<string> result;
        try
        {
                if (num != 0)
                {
                        //Abstraction of a using statement
                }
                try
                {
                        TaskAwaiter<IReadOnlyList<string>> awaiter;
                        if (num != 0)
                        {
                                //Somewhat resembles the actual code
                        }
                        else
                        {
                                awaiter = <>u__1;
                                <>u__1 = default(TaskAwaiter<IReadOnlyList<string>>);
                                num = (<>1__state = -1);
                        }
                        result = awaiter.GetResult();
                }
                finally
                {
                        if (num < 0 && <oLogger>5__2 != null)
                        {
                                <oLogger>5__2.Dispose();
                        }
                }
        }
        catch (Exception exception)
        {
                <>1__state = -2;
                <>t__builder.SetException(exception);
                return;
        }
        <>1__state = -2;
        <>t__builder.SetResult(result);
    }

Is there a way to generate the code as generated by DecompileTypeAsString by decompiling only one function?

I filed an issue on ILSpy and it has been marked as enhancement. So guess it isn't possible at the moment.

I'll go the ugly regex route for now and check back in on the enhancement in later versions.

https://github.com/icsharpcode/ILSpy/issues/1935

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM