Get Custom Attribute - CSharp System.Reflection

CSharp examples for System.Reflection:Attribute

Description

Get Custom Attribute

Demo Code


using System.Threading.Tasks;
using System.Text;
using System.Runtime.Serialization;
using System.Runtime.CompilerServices;
using System.Reflection.Emit;
using System.Reflection;
using System.Linq;
using System.IO;//  w  ww.  j  a v  a  2s .  co  m
using System.Globalization;
using System.Collections.Generic;
using System;

public class Main{
        public static T GetCustomAttribute<T>(this Type type)
            where T : Attribute
        {
            var info = type.GetTypeInfo();
            var data = info.CustomAttributes.Where(a => a.AttributeType == typeof(T)).SingleOrDefault();

            if (data == null) return null;

            var cons = data.Constructor;
            var args = data.ConstructorArguments.Select(a => a.Value).ToArray();
            var ret = cons.Invoke(args);

            return (T)ret;
        }
}

Related Tutorials