反射操作輔助類ReflectionUtil


這篇文章的目的是介紹這樣一種方式,就是在寫一個函數的時候,傳遞的參數是object類型的,在這個函數里面想訪問這個參數對象的某一屬性值,我們知道這個屬性值的name,但是一般情況下,object對象是沒法獲取具體屬性的值的,所以用下面的方式可以獲取。此文章為轉載,原文在:http://lsyyxcn.blog.163.com/blog/static/22740531201002792629559/

 

/// <summary>
    /// 反射操作輔助類
    /// </summary>
    public sealed class ReflectionUtil
    {
        private ReflectionUtil()
        {
        }

        private static BindingFlags bindingFlags = BindingFlags.DeclaredOnly | BindingFlags.Public |
                                                   BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static;

        /**//// <summary>
        /// 執行某個方法
        /// </summary>
        /// <param name="obj">指定的對象</param>
        /// <param name="methodName">對象方法名稱</param>
        /// <param name="args">參數</param>
        /// <returns></returns>
        public static object InvokeMethod(object obj, string methodName, object[] args)
        {
            object objResult = null;
            Type type = obj.GetType();
            objResult = type.InvokeMember(methodName, bindingFlags | BindingFlags.InvokeMethod, null, obj, args);
            return objResult;
        }

        /**//// <summary>
        /// 設置對象字段的值
        /// </summary>
        public static void SetField(object obj, string name, object value)
        {
            FieldInfo fieldInfo = obj.GetType().GetField(name, bindingFlags);
            object objValue = Convert.ChangeType(value, fieldInfo.FieldType);
            fieldInfo.SetValue(objValue, value);
        }

        /**//// <summary>
        /// 獲取對象字段的值
        /// </summary>
        public static object GetField(object obj, string name)
        {
            FieldInfo fieldInfo = obj.GetType().GetField(name, bindingFlags);
            return fieldInfo.GetValue(obj);
        }

        /**//// <summary>
        /// 設置對象屬性的值
        /// </summary>
        public static void SetProperty(object obj, string name, object value)
        {
            PropertyInfo propertyInfo = obj.GetType().GetProperty(name, bindingFlags);
            object objValue = Convert.ChangeType(value, propertyInfo.PropertyType);
            propertyInfo.SetValue(obj, objValue, null);
        }

        /**//// <summary>
        /// 獲取對象屬性的值
        /// </summary>
        public static object GetProperty(object obj, string name)
        {
            PropertyInfo propertyInfo = obj.GetType().GetProperty(name, bindingFlags);
            return propertyInfo.GetValue(obj, null);
        }

        /**//// <summary>
        /// 獲取對象屬性信息(組裝成字符串輸出)
        /// </summary>
        public static string GetProperties(object obj)
        {
            StringBuilder strBuilder = new StringBuilder();
            PropertyInfo[] propertyInfos = obj.GetType().GetProperties(bindingFlags);

            foreach (PropertyInfo property in propertyInfos)
            {
                strBuilder.Append(property.Name);
                strBuilder.Append(":");
                strBuilder.Append(property.GetValue(obj, null));
                strBuilder.Append("\r\n");
            }

            return strBuilder.ToString();
        }
    }

反射操作輔助類ReflectionUtil測試代碼:
    public class TestReflectionUtil
    {
        public static string Execute()
        {
            string result = string.Empty;
            result += "使用ReflectionUtil反射操作輔助類:" + "\r\n";

            try
            {
                Person person = new Person();
                person.Name = "wuhuacong";
                person.Age = 20;
                result += DecriptPerson(person);

                person.Name = "Wade Wu";
                person.Age = 99;
                result += DecriptPerson(person);
            }
            catch (Exception ex)
            {
                result += string.Format("發生錯誤:{0}!\r\n \r\n", ex.Message);
            }
            return result;
        }

        public static string DecriptPerson(Person person)
        {
            string result = string.Empty;

            result += "name:" + ReflectionUtil.GetField(person, "name") + "\r\n";
            result += "age" + ReflectionUtil.GetField(person, "age") + "\r\n";

            result += "Name:" + ReflectionUtil.GetProperty(person, "Name") + "\r\n";
            result += "Age:" + ReflectionUtil.GetProperty(person, "Age") + "\r\n";

            result += "Say:" + ReflectionUtil.InvokeMethod(person, "Say", new object[] {}) + "\r\n";

            result += "操作完成!\r\n \r\n";

            return result;
        }
    }

 

/// <summary>
    /// 反射操作輔助類
    /// </summary>
    public sealed class ReflectionUtil
    {
        private ReflectionUtil()
        {
        }

        private static BindingFlags bindingFlags = BindingFlags.DeclaredOnly | BindingFlags.Public |
                                                   BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static;

        /**//// <summary>
        /// 執行某個方法
        /// </summary>
        /// <param name="obj">指定的對象</param>
        /// <param name="methodName">對象方法名稱</param>
        /// <param name="args">參數</param>
        /// <returns></returns>
        public static object InvokeMethod(object obj, string methodName, object[] args)
        {
            object objResult = null;
            Type type = obj.GetType();
            objResult = type.InvokeMember(methodName, bindingFlags | BindingFlags.InvokeMethod, null, obj, args);
            return objResult;
        }

        /**//// <summary>
        /// 設置對象字段的值
        /// </summary>
        public static void SetField(object obj, string name, object value)
        {
            FieldInfo fieldInfo = obj.GetType().GetField(name, bindingFlags);
            object objValue = Convert.ChangeType(value, fieldInfo.FieldType);
            fieldInfo.SetValue(objValue, value);
        }

        /**//// <summary>
        /// 獲取對象字段的值
        /// </summary>
        public static object GetField(object obj, string name)
        {
            FieldInfo fieldInfo = obj.GetType().GetField(name, bindingFlags);
            return fieldInfo.GetValue(obj);
        }

        /**//// <summary>
        /// 設置對象屬性的值
        /// </summary>
        public static void SetProperty(object obj, string name, object value)
        {
            PropertyInfo propertyInfo = obj.GetType().GetProperty(name, bindingFlags);
            object objValue = Convert.ChangeType(value, propertyInfo.PropertyType);
            propertyInfo.SetValue(obj, objValue, null);
        }

        /**//// <summary>
        /// 獲取對象屬性的值
        /// </summary>
        public static object GetProperty(object obj, string name)
        {
            PropertyInfo propertyInfo = obj.GetType().GetProperty(name, bindingFlags);
            return propertyInfo.GetValue(obj, null);
        }

        /**//// <summary>
        /// 獲取對象屬性信息(組裝成字符串輸出)
        /// </summary>
        public static string GetProperties(object obj)
        {
            StringBuilder strBuilder = new StringBuilder();
            PropertyInfo[] propertyInfos = obj.GetType().GetProperties(bindingFlags);

            foreach (PropertyInfo property in propertyInfos)
            {
                strBuilder.Append(property.Name);
                strBuilder.Append(":");
                strBuilder.Append(property.GetValue(obj, null));
                strBuilder.Append("\r\n");
            }

            return strBuilder.ToString();
        }
    }

反射操作輔助類ReflectionUtil測試代碼:
    public class TestReflectionUtil
    {
        public static string Execute()
        {
            string result = string.Empty;
            result += "使用ReflectionUtil反射操作輔助類:" + "\r\n";

            try
            {
                Person person = new Person();
                person.Name = "wuhuacong";
                person.Age = 20;
                result += DecriptPerson(person);

                person.Name = "Wade Wu";
                person.Age = 99;
                result += DecriptPerson(person);
            }
            catch (Exception ex)
            {
                result += string.Format("發生錯誤:{0}!\r\n \r\n", ex.Message);
            }
            return result;
        }

        public static string DecriptPerson(Person person)
        {
            string result = string.Empty;

            result += "name:" + ReflectionUtil.GetField(person, "name") + "\r\n";
            result += "age" + ReflectionUtil.GetField(person, "age") + "\r\n";

            result += "Name:" + ReflectionUtil.GetProperty(person, "Name") + "\r\n";
            result += "Age:" + ReflectionUtil.GetProperty(person, "Age") + "\r\n";

            result += "Say:" + ReflectionUtil.InvokeMethod(person, "Say", new object[] {}) + "\r\n";

            result += "操作完成!\r\n \r\n";

            return result;
        }
    }


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM