反编译实体类代码

安装Neget包

--.Net FX
Install-Package Dapper Mono.Cecil
Install-Package Dapper ICSharpCode.Decompiler   4.0.5.4521
Install-Package Dapper Microsoft.CodeAnalysis   1.3.2

获取Class代码

using ICSharpCode.Decompiler;
using ICSharpCode.Decompiler.CSharp;
using ICSharpCode.Decompiler.TypeSystem;

namespace Common
{
    public class CodeDecompilerGenerator
    {
        /// <summary>
        /// 获取Class实体代码
        /// </summary>
        /// <param name="dllPath"></param>
        /// <param name="className"></param>
        /// <returns></returns>
        public string CodeDecompiler(string dllPath, string className)
        {
            CSharpDecompiler csharpDecompiler = new CSharpDecompiler(dllPath, new DecompilerSettings());
            FullTypeName fullTypeName = new FullTypeName(className);
            return csharpDecompiler?.DecompileTypeAsString(fullTypeName);
        }
    }
}

获取实体类具体方法代码

using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Common
{
    public class CodeSyntaxHandler
    {
        /// <summary>
        /// 参数
        /// </summary>
        public class Parameter
        {
            /// <summary>
            /// 参数名称
            /// </summary>
            public string ParameterName { get; set; }


            /// <summary>
            /// Type
            /// </summary>
            public Type Type { get; set; }

            /// <summary>
            /// Type名称
            /// </summary>
            public string TypeName { get; set; }
        }

        public string SyntaxAnalysis(string methodName, string classText, List<Parameter> parameters)
        {
            SyntaxTree syntaxTree = CSharpSyntaxTree.ParseText(classText);
            CompilationUnitSyntax compilationUnitSyntax = (CompilationUnitSyntax)syntaxTree.GetRoot();
            List<MethodDeclarationSyntax> list = (from methodDeclaration in compilationUnitSyntax.DescendantNodes().OfType<MethodDeclarationSyntax>()
                                                  where methodDeclaration.Identifier.ValueText == methodName
                                                  && methodDeclaration.ParameterList.Parameters.Count == parameters.Count
                                                  select methodDeclaration).ToList();
            string result = string.Empty;
            var parameterTypeNameList = parameters.Select(p => p.TypeName.ToLower()).ToList();
            foreach (MethodDeclarationSyntax methodDeclaration in list)
            {
                var parameterSyntaxList = methodDeclaration.ParameterList.Parameters.Select(p => p.Type.ToString().ToLower()).ToList();
                if (parameterTypeNameList.Equals(parameterSyntaxList))
                    result = methodDeclaration.ToString();
            }
            if (string.IsNullOrWhiteSpace(result) && list.Count > 0)
            {
                result = list.FirstOrDefault().ToString();
            }
            return result;
        }

    }
}

获取Type名称

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Common
{
    public class TypeHelper
    {
      private  Dictionary<Type, string> typeDic = new Dictionary<Type, string>
{
    { typeof(bool), "bool" },
    { typeof(byte), "byte" },
    { typeof(char), "char" },
    { typeof(decimal), "decimal" },
    { typeof(double), "double" },
    { typeof(float), "float" },
    { typeof(int), "int" },
    { typeof(long), "long" },
    { typeof(sbyte), "sbyte" },
    { typeof(short), "short" },
    { typeof(string), "string" },
    { typeof(uint), "uint" },
    { typeof(ulong), "ulong" },
    { typeof(ushort), "ushort" },
};

        /// <summary>
        /// 获取Type的名称
        /// </summary>
        /// <param name="type"></param>
        /// <returns></returns>
        public string GetTypeName(Type type)
        {
            var name = type.Name;
            if (type.GetGenericArguments().Length.Equals(0) || !type.IsGenericType) return name;
            var str = name.Substring(0, name.IndexOf("`")) + "<" + string.Join(",", type.GetGenericArguments().Select(GetTypeName)) + ">";

            foreach (KeyValuePair<Type, string> keyValuePair in typeDic)
            {
                if (str.Contains(keyValuePair.Key.Name)) str = str.Replace(keyValuePair.Key.Name, keyValuePair.Value);
                if (str.Contains(keyValuePair.Key.FullName)) str = str.Replace(keyValuePair.Key.FullName, keyValuePair.Value);
            }
            return str;
        }
    }
}

反编译程序集


                ModuleDefinition moduleDefinition = ModuleDefinition.ReadModule(@"F:\DownLoad\WebApplication4.dll");
                var typeList = moduleDefinition.Types.ToList();
                foreach (var type in typeList)
                {


                    TypeDefinition typeDefinition = moduleDefinition.Types.FirstOrDefault((TypeDefinition p) => !p.IsPrimitive && p.FullName != "<Module>");
                    typeDefinition = type;

                    foreach (var m in typeDefinition.Methods)
                    {
                        Console.WriteLine(m.Name);
                        Console.WriteLine(m.FullName);
                    }


                    IEnumerable<MethodDefinition> enumerable = from p in typeDefinition.Methods where p.Name != ".ctor" select p;
                    foreach (MethodDefinition methodDefinition in enumerable)
                    {

                        if (methodDefinition.Body == null)
                        {
                            continue;
                        }


                        Console.WriteLine(methodDefinition.Name);
                        Console.WriteLine(methodDefinition.IsAbstract);
                        Console.WriteLine(methodDefinition.IsStatic);
                        Console.WriteLine(methodDefinition.ReturnType.FullName);
                        Console.WriteLine((from p in (from p in methodDefinition.Body.Instructions
                                                      select p.Operand).OfType<MethodReference>()
                                           select p).ToList());
                        Console.WriteLine(GetFieldTypeName(methodDefinition.ReturnType.FullName));
                        Console.WriteLine(methodDefinition.FullName);

                        Console.WriteLine(methodDefinition);
                        Console.WriteLine(methodDefinition.Body);
                        Console.WriteLine(methodDefinition.Body.Instructions);
                        List<FieldDefinition> list = (from p in methodDefinition.Body.Instructions
                                                      select p.Operand).OfType<FieldDefinition>().ToList();

     
                        foreach (ParameterDefinition parameterDefinition in methodDefinition.Parameters)
                        {
                            Console.WriteLine(parameterDefinition.Name);
                            Console.WriteLine(parameterDefinition.ParameterType.FullName);
                        }

                    }
                }
posted @ 2022-07-02 16:08  雨水的命运  阅读(189)  评论(0编辑  收藏  举报