//==============================================================
//  版权所有：深圳杰文科技
//  文件名：AttributeHelper.cs
//  版本：V1.0  
//  创建者：Jay  ( QQ： 85363208 )
//  创建时间：2017-11-28 16:18
//  创建描述：
//  修改者：
//  修改时间：
//  修改说明： 
//==============================================================

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;

namespace Infrastructure.Utilities
{
	/// <summary>
	/// 包含一些与Attribute处理相关的辅助类，以简化Attibute的处理。
	/// </summary>
	public static class AttributeHelper
	{
		public static T GetAttribute<T>(this Type type) where T : Attribute
		{
			object[] attributes = type.GetCustomAttributes(typeof(T), true);
			return (T)attributes.FirstOrDefault();
		}

		/// <summary>
		/// 获得程序集中所有实现了指定Attribute的类和接口的类型。
		/// </summary>
		/// <param name="asm"></param>
		/// <param name="attributeType"></param>
		/// <returns></returns>
		public static List<Type> GetAllType(Assembly asm, Type attributeType)
		{
			List<Type> typeList = new List<Type>();
			Type[] types = asm.GetTypes();
			foreach (Type type in types)
			{
				if (type.IsDefined(attributeType, true))
				{
					typeList.Add(type);
				}
			}
			return typeList;
		}

		public static List<T> GetAllAttribute<T>(this Assembly asm) where T : Attribute
		{
			List<T> list = new List<T>();
			Type[] types = null;
			try
			{
				types = asm.GetTypes();
				foreach (Type type in types)
				{
					object[] objects = type.GetCustomAttributes(typeof(T), true);
					foreach (object obj in objects)
					{
						list.Add((T)obj);
					}
				}
			}
			catch
			{
			}
			return list;
		}

		public static List<object> GetAllAttribute(PropertyInfo pi, Type attributeType)
		{
			return pi.GetCustomAttributes(attributeType, true).ToList();
		}

		public static T Get<T>(MethodInfo mi) where T : Attribute
		{
			object[] objects = mi.GetCustomAttributes(typeof(T), true);
			if (objects.Length > 0)
			{
				return (T)objects[0];
			}
			return default(T);
		}

		public static List<T> GetAllForMethod<T>(Type classType) where T : Attribute
		{
			List<T> list = new List<T>();
			MethodInfo[] methodInfoes = classType.GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
			foreach (MethodInfo mi in methodInfoes)
			{
				T obj = Get<T>(mi);
				list.Add(obj);
			}
			return list;
		}

	}
}
