反編譯實體類代碼

安裝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);
                        }

                    }
                }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章