Find Field In Assembly - CSharp System.Reflection

CSharp examples for System.Reflection:FieldInfo

Description

Find Field In Assembly

Demo Code


using System.Reflection;
using System.Linq;
using System.Collections.Generic;
using System;//from w  w  w  .  j a v a 2s  .co  m

public class Main{

        public static IList<FieldInfo> FindFieldInAssembly<T>(this Assembly assembly, BindingFlags bindingAttr = BindingFlags.Instance | BindingFlags.NonPublic) where T : class
        {
            IList<FieldInfo> datas = new List<FieldInfo>();

            var classTypes = assembly.GetTypes();
            foreach (var item in classTypes)
            {
                var fields = item.GetFields(bindingAttr);
                if (fields.Count() > 0)
                {
                    var fieldType = typeof(T);

                    foreach (var field in fields)
                    {
                        if (field.FieldType.Equals(fieldType))
                        {
                            datas.Add(field);
                        }
                    }
                }
            }

            return datas;
        }
}

Related Tutorials