1. 程式人生 > 其它 >C#將dll中方法通過反射轉換成Url以及反向解析

C#將dll中方法通過反射轉換成Url以及反向解析

最近一個同事問我,他想實現在瀏覽器輸入一個url,執行某個dll中的方法。

這個url的規則很簡單:https://localhost:8080/名稱空間/類名/方法名?param1=2&param2=3.3

遇到這種問題,毫不猶豫,上反射。

        /// <summary>
        /// 解析標準的url,通過反射呼叫對應的名稱空間.類.方法
        /// </summary>
        /// <param name="url"></param>
        /// <param name="dllPath"></param>
public void ResolveUrlAndExcute(string url, string dllPath) { //https://localhost:8080/ClassLibrary1/MyClass/MyMethods?a=2&b=3.3 url = url.Replace("https://localhost:8080/", ""); string[] arr1 = url.Split("?"); string[] arr2 = arr1[0].Split("/");
string typeName = arr2[0] + "." + arr2[1]; string methodName = arr2[2]; List<object> listParameters = new List<object>(); string[] arr3 = arr1[1].Split("&"); foreach(string param in arr3) { listParameters.Add((
object)param.Split("=")[1]); } var assembly = Assembly.LoadFile(dllPath); Type type = assembly.GetType(typeName);// namespace.class if(type != null) { MethodInfo methodInfo = type.GetMethod(methodName);// method name if(methodInfo != null) { object result = null; ParameterInfo[] parameters = methodInfo.GetParameters(); object classInstance = Activator.CreateInstance(type, null); if(parameters.Length == 0) { result = methodInfo.Invoke(classInstance, null); } else { result = methodInfo.Invoke(classInstance, listParameters.ToArray()); } } } }

如果想反向,把每一個方法轉成標準的url,就更簡單了。

        /// <summary>
        /// 把dll中的方法通過反射轉換成url
        /// </summary>
        /// <param name="dllPath"></param>
        /// <returns></returns>
        public static List<string> ComposeRequestUrl(string dllPath)
        {
            List<string> urls = new List<string>();

            var assembly = Assembly.LoadFile(dllPath);
            foreach (var type in assembly.GetTypes())
            {
                string baseUrl = "https://localhost:8080/" + type.Namespace + "/" + type.Name + "/";

                MethodInfo[] myArrayMethodInfo = type.GetMethods(BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance | BindingFlags.DeclaredOnly);

                foreach (var methodInfo in myArrayMethodInfo)
                {
                    string url = baseUrl + methodInfo.Name + "?";
                    string retVal = string.Empty;
                    if (methodInfo != null)
                    {
                        var parameters = methodInfo.GetParameters();
                        foreach (var param in parameters)
                        {
                            url += param.Name + "=&";
                        }
                    }

                    Debug.WriteLine(url.Substring(0, url.Length - 1));
                    urls.Add(url.Substring(0, url.Length - 1));
                }
            }

            return urls;
        }


作者:貓叔Vincent     本文版權歸作者和部落格園共有,歡迎轉載,但未經作者同意必須保留此段宣告,且在文章頁面明顯位置給出原文連線,否則保留追究法律責任的權利。