Exemplo n.º 1
0
        public static T CreateCustomAttribute <T>(this CustomAttributeData attr)
        {
            var attrType = attr.GetAttributeType();
            var obj      = attr.GetConstructor().Invoke(attr.ConstructorArguments.Select(it => it.Value).ToArray());

            if (attr.NamedArguments == null)
            {
                return((T)obj);
            }

            foreach (var arg in attr.NamedArguments)
            {
                if (arg.IsField())
                {
                    var fieldInfo = attrType.GetField(arg.GetMemberName());
                    fieldInfo?.SetValue(obj, GetValue(arg.TypedValue));
                }
                else
                {
                    var propInfo = attrType.GetProperty(arg.GetMemberName());
                    propInfo?.SetValue(obj, GetValue(arg.TypedValue), null);
                }
            }

            return((T)obj);
        }