الفريق العربي للبرمجةأرشيف المنتديات · 2000 – 2023
نسخة أرشيفية للقراءة فقط — التسجيل والمشاركة مغلقان، والمحتوى محفوظ كما كان.

استخدام Reflection Type

بدأه akramKamal في 21 مايو 2010 · 2 رد · 1,556 مشاهدة · في Microsoft Visual C#.NET
مشاركة: واتساب X فيسبوك تيليجرام
#1 صاحب الموضوع

بسم الله الرحمن الرحيم

سنقوم بإذن الله بشرح ال Reflection Type

تدعم لغة السي شارب امكانية التعامل مع الكائنات بطريقة غير مباشرة. فهي تمكنك من عمل كائن جديد من نوع محدد دون الحاجة لاستخدام new() وأيضا بإمكانك أن تقوم باستدعاء دوال أي نوع من خلال اسم الدالة سواء كانت الدالة public أو privite أو أي نوع اخر . أيضا بامكانك الحصول على أسماء الدوال والخصائص لأي نوع.

بعد هذه المقدمة الشيقة نبدأ بصلب الموضوع.

ما سنقوم دراسته في هذا الدرس :

1- الحصول على جميع خصائص النوع Properties و Fields

2- الحصول على جميع الأنواع الداخلية NestedTypes

3- الحصول على الخصائص التى تكتب عند تعريف النوع وتكتب داخل [] وتسمى CustomAttributes

4- الحصول على جميع الأحداث التي في النوع Events

5- الحصول على جميع الدوال Methods

6- انشاء كائن جديد من النوع

7- تغيير قيمة المتغيرات

8- استدعاء أي دالة بمجرد معرفة اسمها

9- تسجيل حدث وازالة التسجيل

لنفترض أن لدينا ال class التالي:

/// <summary>
    ///Custom Attribute
    /// </summary>
    [Serializable]
    class TestType
    {
        /// <summary>
        /// Event
        /// </summary>
        private event EventHandler OnNameChanged;
        /// <summary>
        /// Property
        /// </summary>
        private int Count { get; set; }
        /// <summary>
        /// Field
        /// </summary>
        private string Name;
        /// <summary>
        /// Method
        /// </summary>
        /// <returns></returns>
        private string GetName()
        {
            return Name;
        }
        /// <summary>
        /// Method
        /// </summary>
        /// <param name="name"></param>
        private void SetName(string name)
        {
            this.Name = name;
            if (OnNameChanged != null) OnNameChanged(this, new EventArgs());
        }
    }

سنقوم بتجربة هذا الدرس على هذا ال class

نحتاج الى تعريف متغير من نوع Type

/// <summary>
/// The type to find its fields and properties
/// </summary>
Type TargetType = typeof(TestType);

وأيضا نعرف BindingFlags الذي سنستخدمه في الشرح:

       /// <summary>
       /// Get or set the search for this instance
       /// </summary>	
       public BindingFlags BindingFlags { get; set; }

يستخدم BindingFlags لتحديد البحث. لكن اذا أردت أن يبحث عن أي شي فضع له القيمة التالية AllBindingFlags:

private static BindingFlags _AllBindingFlags;
       private static BindingFlags AllBindingFlags
       {
           get
           {
               if (_AllBindingFlags != BindingFlags.Default) return _AllBindingFlags;
               BindingFlags result=BindingFlags.Default;
               foreach (BindingFlags value in Enum.GetValues(typeof(BindingFlags)))
               {
                   if (value == BindingFlags.IgnoreCase) continue;
                   result |= value;
               }
               _AllBindingFlags = result;
               return result;
           }
       }

للحصول على جميع خصائص النوع Properties و Fields:

/// <summary>
       /// Get all properties infos of TargetType
       /// </summary>
       public List<PropertyInfo> PropertiesInfos
       {
           get
           {
               try
               {
                   return new List<PropertyInfo>(TargetType.GetProperties(BindingFlags));
               }
               catch { return new List<PropertyInfo>(); }
           }
       }
       /// <summary>
       /// Get all fields infos of TargetType
       /// </summary>
       public List<FieldInfo> FieldsInfos
       {
           get
           {
               try
               {
                   return new List<FieldInfo>(TargetType.GetFields(BindingFlags));
               }
               catch { return new List<FieldInfo>(); }
           }
       }

للحصول على جميع الأنواع الداخلية NestedTypes:

/// <summary>
       /// Get all Types of TargetType
       /// </summary>
       public List<Type> NestedTypes
       {
           get
           {
               try { return new List<Type>(TargetType.GetNestedTypes(BindingFlags)); }
               catch { return new List<Type>(); }
           }
       }

للحصول على الخصائص التى تكتب عند تعريف النوع وتكتب داخل [] وتسمى CustomAttributes:

/// <summary>
       /// Get all CustomAttributes of T type
       /// </summary>
       public Dictionary<Type, object> CustomAttributes
       {
           get
           {
               Dictionary<Type, object> temp = new Dictionary<Type, object>();
               try
               {
                   foreach (object attribute in TargetType.GetCustomAttributes(true))
                       temp.Add(attribute.GetType(), attribute);
               }
               catch { }
               return temp;
           }
       }

للحصول على جميع الأحداث التي في النوع Events:

/// <summary>
       /// Get all EventInfo of T type
       /// </summary>
       public List<EventInfo> Events
       {
           get 
           {
               try { return new List<EventInfo>(TargetType.GetEvents(BindingFlags)); }
               catch { return new List<EventInfo>(); }
           }
       }

للحصول على جميع الدوال Methods:

/// <summary>	
       /// Get all EventInfo of T type
       /// </summary>
       public List<MethodInfo> Methods
       {
           get
           {
               try { return new List<MethodInfo>(TargetType.GetMethods(BindingFlags)); }
               catch { return new List<MethodInfo>(); }
           }
       }

انشاء كائن جديد من النوع:

object  newObject = Activator.CreateInstance(TargetType, true);

تغيير قيمة المتغيرات Fields:

/// <summary>
       /// Get the field value and return true if succ
       /// </summary>
       /// <returns></returns>
       public bool GetFieldValue(string fieldName,out object value)
       {
           try
           {
               value=TargetType.GetField(fieldName, BindingFlags).GetValue(TargetObject);
               return true;
           }
           catch { value = null; return false; }
       }

        /// <summary>
        /// Set the field value and return true if succ
        /// </summary>
        /// <returns></returns>
       public bool SetFieldValue(string fieldName,object value)
       {
           try 
           { 
               TargetType.GetField(fieldName, BindingFlags).SetValue(TargetObject, value);
               return true;
           }
           catch { return false; }
       }

تغيير قيمة المتغيرات Properties:

/// <summary>
       /// get the value of property and return true if succ
       /// </summary>
       /// <returns></returns>
       public bool GetPropertyValue(string propertyName, out object value)
       {
           try
           {
               value = TargetType.GetProperty(propertyName, BindingFlags).GetValue(TargetObject, new object[] { });
               return true;
           }
           catch { value = null; return false; }
       }


 /// <summary>
 /// get the value of the index property and return true if succ
       /// </summary>
       /// <returns></returns>
       public bool GetPropertyValue(string propertyName, object[] indexs, out object value)
       {
           try
           {
               value = TargetType.GetProperty(propertyName, BindingFlags).GetValue(TargetObject, indexs);
               return true;
           }
           catch { value = null; return false; }
       }

      /// <summary>
      /// Set the property value and return true if succ
      /// </summary>
      /// <returns></returns>
      public bool SetPropertyValue(string propertyName, object value)
       {
           return SetPropertyValue(propertyName, value, new object[] { });
       }

       /// <summary>
       /// Set indexing property value and return true if succ
       /// </summary>
       /// <param name="propertyName"></param>
       /// <param name="value"></param>
       /// <param name="indexs">Array of indexes that will assign to it this value. </param>
       /// <returns></returns>
       public bool SetPropertyValue(string propertyName, object value, object[] indexs)
       {
           try
           {
               TargetType.GetProperty(propertyName, BindingFlags).SetValue(TargetObject, value, indexs);
               return true;
           }
           catch { return false; }
       }

استدعاء أي دالة بمجرد معرفة اسمها:

      /// <summary>	
       /// Invoke this Method
       /// </summary>
       public bool InvokeMethod(string methodName, object[] parameters,out object methodReturn)
       {
           try
           {
               methodReturn = TargetType.GetMethod(methodName, BindingFlags).Invoke(TargetObject, parameters);
               return true;
           }
           catch 
           {
               methodReturn = null;
               return false; 
           }
       }

تسجيل حدث وازالة التسجيل:

/// <summary>
       /// Add new handler to this event
       /// </summary>
       public bool AddEventHandler(string eventName, Delegate handler)
       {
           try
           {
               TargetType.GetEvent(eventName, BindingFlags).AddEventHandler(TargetObject, handler);
               return true;
           }
           catch { return false; }
       }

       /// <summary>
       /// Remove handler from this event
       /// </summary>
       public bool RemoveEventHandler(string eventName, Delegate handler)
       {
           try
           {
               TargetType.GetEvent(eventName, BindingFlags).RemoveEventHandler(TargetObject, handler);
               return true;
           }
           catch { return false; }

وفي الختام يوجد مثال كامل في المرفقات

AssemblyViewer.rar

5

قولوا لا اله الا الله تفلحوا

ومن يبتغي غير الاسلام دينا فلن يقبل منه وهو في الاخرة من الخاسرين- صدق الله العظيم

#2

شكرا لك أخي بارك الله فيك، أكثر من ممتاز smile.gif

#3

السلام عليكم ورحمه الله وبركاته

شكرا اخي على الموضوع بالفعل الـ Reflection بحر لمن اراد الغوص في عالم الـ IL,Assembly والـ Meta Data

تم تعديل هذه المشاركة بواسطة VB Helper في 10 سبتمبر 2011 في 10:17

.:: Wish to become better and better ::.

مواضيع مشابهة