GetCustomAttributes() public abstract method

public abstract GetCustomAttributes ( Type attributeType, bool inherit ) : Object[]
attributeType Type
inherit bool
return Object[]
示例#1
0
 public static AttributeMap[] Create(TypeModel model, MemberInfo member, bool inherit)
 {
     #if FEAT_IKVM
     System.Collections.Generic.IList<CustomAttributeData> all = member.__GetCustomAttributes(model.MapType(typeof(Attribute)), inherit);
     AttributeMap[] result = new AttributeMap[all.Count];
     int index = 0;
     foreach (CustomAttributeData attrib in all)
     {
         result[index++] = new AttributeDataMap(attrib);
     }
     return result;
     #else
     #if WINRT
     Attribute[] all = System.Linq.Enumerable.ToArray(member.GetCustomAttributes(inherit));
     #else
     var all = member.GetCustomAttributes(inherit);
     #endif
     var result = new AttributeMap[all.Length];
     for (var i = 0; i < all.Length; i++)
     {
         result[i] = new ReflectionAttributeMap((Attribute) all[i]);
     }
     return result;
     #endif
 }
示例#2
0
 private ArgumentHandler ConstructArgumentHandler(MemberInfo info, Argument arg)
 {
     ArgumentHandler ai;
       var memberType = GetMemberType(info);
       var min = 0;
       var max = 0;
       var margs = info.GetCustomAttributes(typeof(MultipleArguments), true) as MultipleArguments[];
       if (margs.Length == 1) {
     min = margs[0].Min;
     max = margs[0].Max;
       }
       if (memberType.IsArray) {
     ai = new ArrayArgumentHandler(this, info, memberType, min, max);
       }
       else if (isIList(memberType)) {
     ai = new IListArgumentHandler(this, info, memberType, min, max);
       }
       else if (memberType == typeof(bool) || memberType == typeof(Boolean) || memberType.IsSubclassOf(typeof(Boolean))) {
     var bargs = info.GetCustomAttributes(typeof(FlagArgument), true) as FlagArgument[];
     ai = new FlagArgumentHandler(this, info, arg.OnCollision, arg.Required, bargs.Length != 0 ? bargs[0].WhenSet : true);
       }
       else if (info.GetCustomAttributes(typeof(CountedArgument), true).Length != 0) {
     ai = new CounterArgumentHandler(this, info, memberType, arg.Required);
       }
       else {
     ai = new PlainArgumentHandler(this, info, memberType, arg.OnCollision, arg.Required);
       }
       return ai;
 }
示例#3
0
		public TestMember(TestType uiTestType, MemberInfo memberInfo)
		{
			DeclaringType = uiTestType;
			MemberInfo = memberInfo;

			// handle public overrides that inherit attributes
			uiTestAttributes = memberInfo.GetCustomAttributes<UiTestAttribute>();
			categoryAttributes = memberInfo.GetCustomAttributes<CategoryAttribute>();
		}
		public static IElasticPropertyAttribute Property(MemberInfo info)
		{
			var attributes = info.GetCustomAttributes(typeof(IElasticPropertyAttribute), true);
			if (attributes != null && attributes.Any())
				return ((IElasticPropertyAttribute)attributes.First());

			var ignoreAttrutes = info.GetCustomAttributes(typeof(JsonIgnoreAttribute), true);
			if (ignoreAttrutes != null && ignoreAttrutes.Any())
				return new ElasticPropertyAttribute { OptOut = true };

			return null;
		}
示例#5
0
      private String GetMemberName (MemberInfo memberInfo)
      {
         DirectApiAttribute directApiAttribute =
            memberInfo.GetCustomAttributes(false).OfType<DirectApiAttribute>().FirstOrDefault();

         return directApiAttribute == null ? memberInfo.Name : directApiAttribute.Name;
      }
示例#6
0
        /// <summary>
        /// Examines the designated object type using reflections, extracts any defined
        /// TableAttribute and ColumnAttribute attributes, and builds a new
        /// TableSchema object that represents the database mappings for the type.
        /// </summary>
        /// <returns>The table schema defined for the designated object type.</returns>
        /// <remarks>This schema is used to generate standard Select and CRUD (Create,
        /// Update and Delete) commands and to rollback changes when an edit is
        /// aborted.</remarks>
        public static TableSchema <T> GetSchema()
        {
            TableSchema <T> schema = new TableSchema <T>();

            // use reflection to extract custom attributes from designated type
            System.Reflection.MemberInfo inf = typeof(T);

            // Get Table attribute
            object[] tableattributes;
            tableattributes = inf.GetCustomAttributes(typeof(Framework.TableAttribute), false);
            if (tableattributes.Length != 1)
            {
                throw new Exception("Unable to get schema for business object, missing Table attribute.");
            }
            schema._table = (TableAttribute)tableattributes[0];

            // Get Column attributes
            schema._cols = new Dictionary <string, ColumnAttribute>();
            schema._keys = new Dictionary <string, ColumnAttribute>();
            PropertyInfo[] props = typeof(T).GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
            if (props.Length == 0)
            {
                throw new Exception("Target type does not have any properties.");
            }
            foreach (PropertyInfo prop in props)
            {
                object[] columnattributes;
                columnattributes = prop.GetCustomAttributes(typeof(Framework.ColumnAttribute), false);
                if (columnattributes.Length > 0)
                {
                    ColumnAttribute col = (ColumnAttribute)columnattributes[0];
                    if (col.IsPrimaryKey)
                    {
                        schema._keys.Add(prop.Name, col);
                    }
                    schema._cols.Add(prop.Name, col);
                    if (col.IsDBGenerated)
                    {
                        schema._isAnyDBGenerated = true;
                    }
                    if (col.IsVersion)
                    {
                        schema._versioncolumn = prop.Name;
                    }
                    if (col.IsDBGenerated && col.IsPrimaryKey)
                    {
                        schema._identitycolumn = prop.Name;
                    }
                }
            }
            if (schema._cols.Count == 0)
            {
                throw new Exception("Target type does not define any data columns.");
            }
            if (schema._keys.Count == 0)
            {
                throw new Exception("Target type does not define any primary key columns.");
            }
            return(schema);
        }
        private static bool HasAliasAttribute(string alias, MemberInfo member)
        {
            var attributes = member.GetCustomAttributes(true);
            var dataMember = attributes.OfType<DataMemberAttribute>()
                .FirstOrDefault();
            if (dataMember != null && dataMember.Name == alias)
            {
                return true;
            }

            var xmlElement = attributes.OfType<XmlElementAttribute>()
                .FirstOrDefault();
            if (xmlElement != null && xmlElement.ElementName == alias)
            {
                return true;
            }

            var xmlAttribute = attributes.OfType<XmlAttributeAttribute>()
                .FirstOrDefault();
            if (xmlAttribute != null && xmlAttribute.AttributeName == alias)
            {
                return true;
            }
            return false;
        }
示例#8
0
        private bool GetAttrValue(System.Reflection.MemberInfo member, System.Type type, string name, out object value)
        {
            value = null;
            XmlAttribute xmlAttribute = this.node.Attributes[name];
            bool         result;

            if (xmlAttribute != null)
            {
                string value2 = xmlAttribute.Value;
                if (!string.IsNullOrEmpty(value2))
                {
                    value  = System.Convert.ChangeType(value2, type);
                    result = true;
                    return(result);
                }
            }
            else
            {
                object[] customAttributes = member.GetCustomAttributes(false);
                object[] array            = customAttributes;
                for (int i = 0; i < array.Length; i++)
                {
                    object obj = array[i];
                    if (obj is DefaultValueAttribute)
                    {
                        value  = ((DefaultValueAttribute)obj).Value;
                        result = true;
                        return(result);
                    }
                }
            }
            result = false;
            return(result);
        }
		/// <summary>
		/// Initializes a new instance of the ClassPropInfo class.
		/// </summary>
		/// <param name="memberInfo">The member to represent.</param>
		private ClassPropInfo(MemberInfo memberInfo)
		{
			Type = memberInfo.ReflectedType;
			Name = memberInfo.Name.ToUpperInvariant();

			// try to look up a field with the name
			FieldInfo = memberInfo as FieldInfo;
			if (FieldInfo != null)
			{
				MemberType = FieldInfo.FieldType;
			}
			else
			{
				// get the property
				PropertyInfo p = memberInfo as PropertyInfo;

				// get the getter and setter
				GetMethodInfo = p.GetGetMethod(true);
				SetMethodInfo = p.GetSetMethod(true);

				MemberType = p.PropertyType;
			}

			// see if there is a column attribute defined on the field
			var attribute = memberInfo.GetCustomAttributes(typeof(ColumnAttribute), true).OfType<ColumnAttribute>().FirstOrDefault();
			ColumnName = (attribute != null) ? attribute.ColumnName.ToUpperInvariant() : Name;
		}
示例#10
0
        internal bool IsMemberRequired(MemberInfo memberInfo)
        {
            bool retVal = false;

            if (memberInfo.GetCustomAttributes(true).Any(q => q is RequiredAttribute))
            {
                retVal = true;
            }
            else if (true)
            {
                PropertyInfo propertyInfo = memberInfo as PropertyInfo;
                FieldInfo fieldInfo = memberInfo as FieldInfo;

                if (propertyInfo != null)
                {
                    if (propertyInfo.PropertyType.IsValueType &&
                    !(propertyInfo.PropertyType.IsGenericType && propertyInfo.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>)))
                    {
                        retVal = true;
                    }
                }
                else if (fieldInfo != null)
                {
                    if (fieldInfo.FieldType.IsValueType &&
                    !(fieldInfo.FieldType.IsGenericType && fieldInfo.FieldType.GetGenericTypeDefinition() == typeof(Nullable<>)))
                    {
                        retVal = true;
                    }
                }
            }

            return retVal;
        }
        static StackObject *GetCustomAttributes_6(ILIntepreter __intp, StackObject *__esp, IList <object> __mStack, CLRMethod __method, bool isNewObj)
        {
            ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain;
            StackObject *ptr_of_this_method;
            StackObject *__ret = ILIntepreter.Minus(__esp, 3);

            ptr_of_this_method = ILIntepreter.Minus(__esp, 1);
            System.Boolean @inherit = ptr_of_this_method->Value == 1;

            ptr_of_this_method = ILIntepreter.Minus(__esp, 2);
            System.Type @attributeType = (System.Type) typeof(System.Type).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack));
            __intp.Free(ptr_of_this_method);

            ptr_of_this_method = ILIntepreter.Minus(__esp, 3);
            System.Reflection.MemberInfo instance_of_this_method = (System.Reflection.MemberInfo) typeof(System.Reflection.MemberInfo).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack));
            __intp.Free(ptr_of_this_method);

            var result_of_this_method = instance_of_this_method.GetCustomAttributes(true);

            //这里需要对反射进行改造,使其没那么残疾
            List <object> ret = new List <object>();

            foreach (var r in result_of_this_method)
            {
                var iltype = r as ILTypeInstance;
                if (iltype != null && iltype.Type.FullName == @attributeType.AssemblyQualifiedName)
                {
                    ret.Add(r);
                }
            }
            return(ILIntepreter.PushObject(__ret, __mStack, ret.ToArray()));
        }
		// Nasty hack to work around not referencing DataAnnotations directly. 
		// At some point investigate the DataAnnotations reference issue in more detail and go back to using the code above. 
		static string GetDisplayName(MemberInfo member) {
			var attributes = (from attr in member.GetCustomAttributes(true)
			                  select new {attr, type = attr.GetType()}).ToList();

			string name = null;

#if !WINDOWS_PHONE
			name = (from attr in attributes
			        where attr.type.Name == "DisplayAttribute"
			        let method = attr.type.GetRuntimeMethod("GetName", new Type[0]) 
			        where method != null
			        select method.Invoke(attr.attr, null) as string).FirstOrDefault();
#endif

#if !SILVERLIGHT
			if (string.IsNullOrEmpty(name)) {
				name = (from attr in attributes
				        where attr.type.Name == "DisplayNameAttribute"
				        let property = attr.type.GetRuntimeProperty("DisplayName")
				        where property != null
				        select property.GetValue(attr.attr, null) as string).FirstOrDefault();
			}
#endif

			return name;
		}
示例#13
0
    static WorkshopCodeAttribute GetWorkshopCodeAttribute(System.Reflection.MemberInfo targetMethod)
    {
        var attributes            = targetMethod?.GetCustomAttributes(typeof(WorkshopCodeAttribute), true);
        var workshopCodeAttribute = (attributes?.FirstOrDefault() as WorkshopCodeAttribute);

        return(workshopCodeAttribute);
    }
 private bool ShouldIgnore(MemberInfo member)
 {
     var attr = member.GetCustomAttributes(typeof(SerializeIgnoreAttribute), true).SingleOrDefault();
     if (attr != null)
         return (attr as SerializeIgnoreAttribute).IgnoreTypes.Contains(_ignoreType);
     return false;
 }
示例#15
0
        private string GetPropStr(System.Reflection.MemberInfo member, object value)
        {
            object[] customAttributes = member.GetCustomAttributes(false);
            object[] array            = customAttributes;
            string   result;

            for (int i = 0; i < array.Length; i++)
            {
                object obj = array[i];
                if (obj is DefaultValueAttribute)
                {
                    object value2 = ((DefaultValueAttribute)obj).Value;
                    if (object.Equals(value, value2))
                    {
                        result = "";
                        return(result);
                    }
                }
            }
            if (value == null)
            {
                result = "";
                return(result);
            }
            string text = value.ToString();

            if (value is bool)
            {
                text = text.ToLower();
            }
            result = text;
            return(result);
        }
示例#16
0
 public static string GetOpenTypeDescription(MemberInfo typeElement)
 {
     Type typeToQuery;
      if (typeElement.MemberType == MemberTypes.TypeInfo || typeElement.MemberType == MemberTypes.NestedType)
      {
     typeToQuery = (Type)typeElement;
      }
      else
      {
     typeToQuery = typeElement.DeclaringType;
      }
      if (typeToQuery.IsDefined(typeof(OpenTypeAttribute), true))
      {
     OpenTypeAttribute mappingSpec =
        (OpenTypeAttribute) typeToQuery.GetCustomAttributes(typeof (OpenTypeAttribute), true)[0];
     if (!string.IsNullOrEmpty(mappingSpec.ResourceName))
     {
        ResourceManager manager = new ResourceManager(mappingSpec.ResourceName, typeToQuery.Assembly);
        string descr = manager.GetString(typeElement.Name);
        if (descr == null)
        {
           throw new MissingResourceItemException(typeElement.Name, mappingSpec.ResourceName,
                                                  typeToQuery.Assembly.FullName);
        }
        return descr;
     }
      }
      if (typeElement.IsDefined(typeof(DescriptionAttribute), true))
      {
     DescriptionAttribute descrAttr =
        (DescriptionAttribute) typeElement.GetCustomAttributes(typeof (DescriptionAttribute), true)[0];
     return descrAttr.Description;
      }
      return typeElement.Name;
 }
        public static bool ContainsCustomAttribute <T>(this System.Reflection.MemberInfo type, bool inherit = false)
            where T : System.Attribute
        {
            var attributes = type.GetCustomAttributes <T>(inherit);

            return(attributes.Any());
        }
示例#18
0
        internal static TypeAttributeMapping FromMember(TypeMapping declaringType, MemberInfo memberInfo)
        {
            string name = null;
            SqlType sqlType = GetSqlType(memberInfo);
            int size = -1;
            int scale = -1;
            bool nullable = true;

            object[] attrs = memberInfo.GetCustomAttributes(true);
            for (int i = 0; i < attrs.Length; i++) {
                object attr = attrs[i];

                if (attr is ColumnAttribute) {
                    ColumnAttribute columnAttr = (ColumnAttribute)attr;
                    name = columnAttr.ColumnName;
                    sqlType = columnAttr.SqlType;
                    size = columnAttr.Size;
                    scale = columnAttr.Scale;
                } else if (attr is NotNullAttribute) {
                    nullable = false;
                }
            }

            TType type = GetTType(sqlType, size, scale);

            return new TypeAttributeMapping(declaringType, name, type, nullable);
        }
示例#19
0
            static bool SignalFilter(System.Reflection.MemberInfo m, object filterCriteria)
            {
                string signame = (filterCriteria as string);

                object[] attrs = m.GetCustomAttributes(typeof(GLib.SignalAttribute), false);
                if (attrs.Length > 0)
                {
                    foreach (GLib.SignalAttribute a in attrs)
                    {
                        if (signame == a.CName)
                        {
                            return(true);
                        }
                    }
                    return(false);
                }
                else
                {
                    /* this tries to match the names when no attibutes are present.
                     * It is only a fallback. */
                    signame = signame.ToLower().Replace("_", "");
                    string evname = m.Name.ToLower();
                    return(signame == evname);
                }
            }
		public void Parse (MemberInfo aMember)
		{
			object[] attrs = aMember.GetCustomAttributes (false);
			foreach (object attr in attrs)
				if (TypeValidator.IsCompatible(attr.GetType(), typeof(DevelopmentInformationAttribute)) == true)
					members.Add ((DevelopmentInformationAttribute) attr);
		}
示例#21
0
        static void Main(string[] args)
        {
            System.Reflection.MemberInfo info = typeof(Entity);
            //显示附加到类 Entity 上的自定义特性
            object[] objs = info.GetCustomAttributes(true);
            foreach (var obj in objs)
            {
                Console.WriteLine(obj);
            }
            Entity entity = new Entity("hhm");
            Type   type   = entity.GetType();

            foreach (MethodInfo m in type.GetMethods())
            {
                foreach (Attribute a in m.GetCustomAttributes(typeof(FildAttribute), false))
                {
                    FildAttribute fild = (FildAttribute)a;
                    if (null != fild)
                    {
                        //fild.F_Name是attribute设置的名字,m.Name是函数的名字
                        Console.WriteLine("fild.F_Name{0},Name{1}", fild.F_Name, m.Name);
                        Console.WriteLine(fild.F_Style);
                    }
                }
            }
            Console.ReadKey();
        }
        internal static CsvMapToColumns FindInMember(MemberInfo member)
        {
            CsvMapToColumns csvMapToColumns = null;

            object[] attributes = member.GetCustomAttributes(typeof(CsvMapToColumns), false);
            if (attributes != null && attributes.Length > 0) 
            {
                if (attributes.Length > 1) 
                {
                    throw new Exception (string.Format ("Multiple {0} attributes assigned to propery: {1}", 
                                                        typeof(CsvMapToColumns).Name, 
                                                        member.Name));
                }

                if (member.MemberType.Equals(typeof(KeyValuePair<string, object>)))
                {
                    throw new Exception (string.Format ("{0} attribute assigned to propery {1} must be of type: KeyValuePair<string, object>", 
                                                        typeof(CsvMapToColumns).Name, 
                                                        member.Name));
                }
                csvMapToColumns = attributes[0] as CsvMapToColumns;
            }

            return csvMapToColumns;
        }
示例#23
0
        public ServiceShell()
        {
            try
            {
                //Trace.WriteLine("Get service name");
                System.Reflection.MemberInfo info = GetType();
                var attribs = info.GetCustomAttributes(typeof(ServiceAttribute), true);
                //Trace.WriteLine("attribs: " + attribs.Length);
                for (int i = 0; i < attribs.Length; i++)
                {
                    ServiceName = ((ServiceAttribute)attribs[i]).ServiceName;
                    break;
                }

                Trace.WriteLine(ServiceName);

                CanStop             = true;
                CanPauseAndContinue = false;
                CanShutdown         = true;
                AutoLog             = true;
                Trace.WriteLine("constructor done");
                InitializeComponent();
            }
            catch (Exception ex)
            {
                throw new Exception("isntall error!", ex);
            }
        }
示例#24
0
        private static void AddMember(ServiceAssembly assembly, ServiceTypeFieldCollection result, MemberInfo member, Type memberType)
        {
            var attributes = member.GetCustomAttributes(typeof(ProtoMemberAttribute), true);

            if (attributes.Length == 0)
                return;

            Debug.Assert(attributes.Length == 1);

            var attribute = (ProtoMemberAttribute)attributes[0];

            var shouldSerializeMember = member.DeclaringType.GetMethod(
                "ShouldSerialize" + member.Name,
                BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic
            );

            result.Add(new ServiceTypeField(
                assembly,
                ReflectionOptimizer.BuildGetter(member),
                ReflectionOptimizer.BuildSetter(member, true),
                shouldSerializeMember == null ? null : ReflectionOptimizer.BuildShouldSerializeInvoker(shouldSerializeMember),
                attribute.Tag,
                attribute.IsRequired,
                memberType
            ));
        }
示例#25
0
 private void IncludeTypes(MemberInfo memberInfo, RecursionLimiter limiter)
 {
     foreach (Attribute attr in memberInfo.GetCustomAttributes(typeof(SoapIncludeAttribute), false))
     {
         IncludeType(((SoapIncludeAttribute)attr).Type, limiter);
     }
 }
        public static T[] GetAttributesAndPropertyAttributesInterface <T>(this System.Reflection.MemberInfo member,
                                                                          bool inherit = false)
        {
            if (!typeof(T).IsInterface)
            {
                throw new ArgumentException($"{typeof(T).FullName} is not an interface.");
            }
            var attributes = member.GetCustomAttributes(inherit)
                             .Where(attr => typeof(T).IsAssignableFrom(attr.GetType()))
                             .Select(attr => (T)attr)
                             .ToArray();

            var memberAttributes = GetMemberAttributes();

            return(attributes.Concat(memberAttributes).Distinct().ToArray());

            IEnumerable <T> GetMemberAttributes()
            {
                foreach (var subMember in member.GetMemberType().GetMembers(BindingFlags.Public))
                {
                    foreach (var attr in subMember.GetAttributesInterface <T>(inherit))
                    {
                        yield return(attr);
                    }
                }
            }
        }
        /// <summary>
        /// Creates a <see cref="T:Newtonsoft.Json.Serialization.JsonProperty"/> for the given <see cref="T:System.Reflection.MemberInfo"/>.
        /// </summary>
        /// <param name="memberSerialization">The member's parent <see cref="T:Newtonsoft.Json.MemberSerialization"/>.</param><param name="member">The member to create a <see cref="T:Newtonsoft.Json.Serialization.JsonProperty"/> for.</param>
        /// <returns>
        /// A created <see cref="T:Newtonsoft.Json.Serialization.JsonProperty"/> for the given <see cref="T:System.Reflection.MemberInfo"/>.
        /// </returns>
        protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
        {
            var jsonProp = base.CreateProperty(member, memberSerialization);

            var sfAttrs = member.GetCustomAttributes(typeof(SalesForceAttribute), true);

            // if there are no attr then no need to process any further
            if (!sfAttrs.Any()) return jsonProp;

            var sfAttr = sfAttrs.FirstOrDefault() as SalesForceAttribute;
            // if there are no attr then no need to process any further
            if (sfAttr == null)
            {
                return jsonProp;
            }

            // if ignore then we should skip it and return null
            if (sfAttr.Ignore || (updateResolver && sfAttr.IgnoreUpdate))
            {
                return null;
            }

            // if no fieldname then we use the default
            if (string.IsNullOrEmpty(sfAttr.FieldName))
            {
                return jsonProp;
            }

            jsonProp.PropertyName = sfAttr.FieldName;

            return jsonProp;
        }
        public static T[] GetAttributesInterface <T>(this System.Reflection.MemberInfo type,
                                                     bool inherit  = false,
                                                     bool multiple = false)
        {
            if (!typeof(T).IsInterface)
            {
                throw new ArgumentException($"{typeof(T).FullName} is not an interface.");
            }
            var attributes = type.GetCustomAttributes(inherit)
                             .Where(attr => typeof(T).IsAssignableFrom(attr.GetType()))
                             .Select(attr => (T)attr)
                             .ToArray();

            if (!multiple)
            {
                return(attributes);
            }
            if (!(type is Type))
            {
                return(attributes);
            }
            var typeType = type as Type;

            if (typeType.BaseType.IsDefaultOrNull())
            {
                return(attributes);
            }
            var baseAttrs = typeType.BaseType.GetAttributesInterface <T>(inherit, multiple);

            return(attributes.Concat(baseAttrs).Distinct().ToArray());
        }
示例#29
0
        /// <summary>
        /// Returns a value indicating whether the value of the specified field will be excluded from a list.
        /// </summary>
        /// <param name="mi">The field to check.</param>
        /// <returns>
        /// true if the value of the specified field will be excleded from a list; otherwise, false.
        /// </returns>
        /// <exception cref="System.NullReferenceException">
        /// Object reference not set to an instance of an object.
        /// </exception>
        public static bool IsExcluded(MemberInfo mi)
        {
            if (mi == null)
                return false;

            return (mi.GetCustomAttributes(typeof(ExcludeAttribute), false).Length > 0);
        }
		/// <summary>
		/// Collects the resources.
		/// </summary>
		/// <param name="memberInfo">The member info.</param>
		/// <returns></returns>
		public ResourceDescriptor[] CollectResources(MemberInfo memberInfo)
		{
			if (logger.IsDebugEnabled)
			{
				logger.DebugFormat("Collecting resources information for {0}", memberInfo.Name);
			}
			
			object[] attributes = memberInfo.GetCustomAttributes(typeof(IResourceDescriptorBuilder), true);

			ArrayList descriptors = new ArrayList();

			foreach(IResourceDescriptorBuilder builder in attributes)
			{
				ResourceDescriptor[] descs = builder.BuildResourceDescriptors();
				
				if (logger.IsDebugEnabled)
				{
					foreach(ResourceDescriptor desc in descs)
					{
						logger.DebugFormat("Collected resource {0} Assembly Name {1} Culture {2} ResName {3} ResType {4}",
						                   desc.Name, desc.AssemblyName, desc.CultureName, desc.ResourceName, desc.ResourceType);
					}
				}
				
				descriptors.AddRange(descs);
			}

			return (ResourceDescriptor[]) descriptors.ToArray(typeof(ResourceDescriptor));
		}
        /// <summary>
        /// Returns the attributes on <paramref name="member"/> that this convention applies to.
        /// </summary>
        /// <param name="member"></param>
        /// <returns></returns>
        public Attribute[] GetAttributes(MemberInfo member)
        {
            if (member == null)
            {
                throw Error.ArgumentNull("member");
            }

            Attribute[] attributes =
                member
                .GetCustomAttributes(inherit: true)
                .OfType<Attribute>()
                .Where(AttributeFilter)
                .ToArray();

            if (!AllowMultiple && attributes.Length > 1)
            {
                throw Error.InvalidOperation(
                    SRResources.MultipleAttributesFound,
                    member.Name,
                    member.ReflectedType.Name,
                    attributes.First().GetType().Name);
            }

            return attributes;
        }
示例#32
0
    protected void ProcessAttributes()
    {
        m_allowedTypes = new List <Type>();
        int count = 0;

        System.Reflection.MemberInfo info = GetType();
        //B-Se pone true por los tuyos y los heredados
        object[] attributes = info.GetCustomAttributes(true);

        //Version 4.5 - info.GetCustomAttribute<AllowedTypeToStorage>();

        for (int i = 0; i < attributes.Length; ++i)
        {
            if (attributes[i].GetType() == typeof(AllowedTypeToStorage))
            {
                //TODO 1: Añadir a la lista de atributos permitidos. (solucion 001)
                AllowedTypeToStorage allowedType = attributes[i] as AllowedTypeToStorage;
                m_allowedTypes.Add(allowedType.m_type);

                count++;
            }
        }

        Debug.Assert(count > 0, "Error: It Must be defined a Allowed types Attributes");
    }
示例#33
0
        /// <summary>
        ///   Get attributes for the member.
        /// </summary>
        /// <param name="memberInfo">
        ///   A <b>MemberInfo</b> value.
        /// </param>
        /// <returns>
        ///   A <b>string</b> value contains the attributs for this member.
        /// </returns>
        public static string GetAttributesForMember(MemberInfo memberInfo)
        {
            // Check parameters.
            if (memberInfo == null)
            {
                throw new ArgumentNullException();
            }

            // Get attributes used for this method.
            Object[] attributes = memberInfo.GetCustomAttributes(false);
            if (attributes.Length < 1)
            {
                return null;
            }
            else if (attributes.Length == 1)
            {
                return " (" + attributes[0].GetType().Name + ")";
            }
            else
            {
                string attNames = " (";
                foreach (object o in attributes)
                {
                    attNames += o.GetType().Name + ",";
                }
                attNames = attNames.Substring(0, attNames.Length - 1);
                attNames += ")";
                return attNames;
            }
        }
示例#34
0
        private static string ToStringImpl(MemberInfo member, Object value)
        {
            if (value == null)
                return "null";

            var fileSizeAttr = member.GetCustomAttributes(typeof (FileSizeAttribute), false)
                                     .OfType<FileSizeAttribute>()
                                     .FirstOrDefault();

            if (fileSizeAttr != null)
            {
                if (value is long)
                    return fileSizeAttr.Format((long) value);
                if (value is ulong)
                    return fileSizeAttr.Format((ulong) value);
            }

            var collection = value as ICollection<Object>;
            if (collection != null)
            {
                return string.Format("[ {0} ]", string.Join(", ", collection));
            }

            var str = value.ToString();
            var lines = Regex.Split(str, @"[\n\r\f]+");

            if (lines.Count() > 1)
                str = Environment.NewLine + string.Join(Environment.NewLine, lines.Select(s => "    " + s));

            return str;
        }
 private static void FillCorrelationAliasAttrs(MemberInfo memberInfo, Hashtable correlationAliasAttrs, ValidationErrorCollection validationErrors)
 {
     foreach (object obj2 in memberInfo.GetCustomAttributes(typeof(CorrelationAliasAttribute), false))
     {
         CorrelationAliasAttribute attributeFromObject = Helpers.GetAttributeFromObject<CorrelationAliasAttribute>(obj2);
         if (string.IsNullOrEmpty(attributeFromObject.Name) || (attributeFromObject.Name.Trim().Length == 0))
         {
             ValidationError item = new ValidationError(SR.GetString(CultureInfo.CurrentCulture, "Error_CorrelationAttributeInvalid", new object[] { typeof(CorrelationAliasAttribute).Name, "Name", memberInfo.Name }), 0x150);
             item.UserData.Add(typeof(CorrelationAliasAttribute), memberInfo.Name);
             validationErrors.Add(item);
         }
         else if (string.IsNullOrEmpty(attributeFromObject.Path) || (attributeFromObject.Path.Trim().Length == 0))
         {
             ValidationError error2 = new ValidationError(SR.GetString(CultureInfo.CurrentCulture, "Error_CorrelationAttributeInvalid", new object[] { typeof(CorrelationAliasAttribute).Name, "Path", memberInfo.Name }), 0x150);
             error2.UserData.Add(typeof(CorrelationAliasAttribute), memberInfo.Name);
             validationErrors.Add(error2);
         }
         else if (correlationAliasAttrs.Contains(attributeFromObject.Name))
         {
             ValidationError error3 = new ValidationError(SR.GetString(CultureInfo.CurrentCulture, "Error_DuplicateCorrelationAttribute", new object[] { typeof(CorrelationAliasAttribute).Name, attributeFromObject.Name, memberInfo.Name }), 0x151);
             error3.UserData.Add(typeof(CorrelationAliasAttribute), memberInfo.Name);
             validationErrors.Add(error3);
         }
         else
         {
             correlationAliasAttrs.Add(attributeFromObject.Name, attributeFromObject);
         }
     }
 }
		/// <summary>
		/// Implementors should collect the transformfilter information
		/// and return descriptors instances, or an empty array if none
		/// was found.
		/// </summary>
		/// <param name="memberInfo">The action (MethodInfo)</param>
		/// <returns>
		/// An array of <see cref="TransformFilterDescriptor"/>
		/// </returns>
		public TransformFilterDescriptor[] CollectFilters(MemberInfo memberInfo)
		{
			if (logger.IsDebugEnabled)
			{
				logger.DebugFormat("Collecting filters for {0}", memberInfo.Name);
			}

			object[] attributes = memberInfo.GetCustomAttributes(typeof(ITransformFilterDescriptorBuilder), true);

			ArrayList filters = new ArrayList();

			foreach (ITransformFilterDescriptorBuilder builder in attributes)
			{
				TransformFilterDescriptor[] descs = builder.BuildTransformFilterDescriptors();

				if (logger.IsDebugEnabled)
				{
					foreach (TransformFilterDescriptor desc in descs)
					{
						logger.DebugFormat("Collected filter {0} to execute in order {1}",desc.TransformFilterType, desc.ExecutionOrder);
					}
				}

				filters.AddRange(descs);
			}

			return (TransformFilterDescriptor[])filters.ToArray(typeof(TransformFilterDescriptor));
		}
 private static void ShowAttributes(MemberInfo attributeTarget)
 {
     var attributes = attributeTarget.GetCustomAttributes<Attribute>();
     Console.WriteLine("Attributes applied to {0}: {1}",
     attributeTarget.Name, (attributes.Count() == 0 ? "None" : String.Empty));
     foreach (Attribute attribute in attributes)
     {
         // Вывод типа всех примененных атрибутов
         Console.WriteLine(" {0}", attribute.GetType().ToString());
         if (attribute is DefaultMemberAttribute)
             Console.WriteLine(" MemberName={0}",
             ((DefaultMemberAttribute)attribute).MemberName);
         if (attribute is ConditionalAttribute)
             Console.WriteLine(" ConditionString={0}",
         ((ConditionalAttribute)attribute).ConditionString);
         if (attribute is CLSCompliantAttribute)
             Console.WriteLine(" IsCompliant={0}",
             ((CLSCompliantAttribute)attribute).IsCompliant);
         DebuggerDisplayAttribute dda = attribute as DebuggerDisplayAttribute;
         if (dda != null)
         {
             Console.WriteLine(" Value={0}, Name={1}, Target={2}",
             dda.Value, dda.Name, dda.Target);
         }
     }
     Console.WriteLine();
 }
示例#38
0
        private static void ReflectAttr_early()
        {
            Console.WriteLine();
            Console.WriteLine("Early Binding");

            System.Reflection.MemberInfo info = typeof(Crow);
            object[] attributes = info.GetCustomAttributes(true);
            for (int i = 0; i < attributes.Length; i++)
            {
                System.Console.WriteLine(attributes[i]);
            }

            Console.WriteLine();
            Type tat = typeof(Crow);

            if (Attribute.IsDefined(tat, typeof(BirdSpeciesAttribute)))
            {
                var attributeValue = Attribute.GetCustomAttribute(tat, typeof(BirdSpeciesAttribute)) as BirdSpeciesAttribute;
                Console.WriteLine("BirdSpeciesAttribute - {0}\n", attributeValue.Classification);
            }

            if (Attribute.IsDefined(tat, typeof(System.SerializableAttribute)))
            {
                var attributeValue = Attribute.GetCustomAttribute(tat, typeof(System.SerializableAttribute)) as System.SerializableAttribute;
                Console.WriteLine("Serializable - {0}\n", attributeValue.TypeId);
            }
        }
示例#39
0
        public static ColumnInfo FromMemberInfo(MemberInfo mi)
        {
            // Check if declaring/reflected poco has [Explicit] attribute
            var a = mi.ReflectedType.GetCustomAttributes(typeof(ExplicitColumnsAttribute), true);
            bool ExplicitColumns = mi.DeclaringType.GetCustomAttributes(typeof(ExplicitColumnsAttribute), true).Any()
                || a.Length != 0 && (a[0] as ExplicitColumnsAttribute).ApplyToBase;

            // Check for [Column]/[Ignore] Attributes
            var ColAttrs = mi.GetCustomAttributes(typeof(ColumnAttribute), true);
            if (ExplicitColumns)
            {
                if (ColAttrs.Length == 0)
                    return null;
            }
            else
            {
                if (mi.GetCustomAttributes(typeof(IgnoreAttribute), true).Length != 0)
                    return null;
            }

            ColumnInfo ci = new ColumnInfo();

            // Read attribute
            if (ColAttrs.Length > 0)
            {
                var colattr = (ColumnAttribute)ColAttrs[0];

                ci.ColumnName = colattr.Name ?? mi.Name;
                ci.ForceToUtc = colattr.ForceToUtc;
                if ((colattr as ResultColumnAttribute) != null)
                    ci.ResultColumn = true;
            }
            else
            {
                ci.ColumnName = mi.Name;
                ci.ForceToUtc = false;
                ci.ResultColumn = false;
            }

            var columnTypeAttr = mi.GetCustomAttributes(typeof(ColumnTypeAttribute), true);
            if (columnTypeAttr.Any())
            {
                ci.ColumnType = ((ColumnTypeAttribute)columnTypeAttr[0]).Type;
            }

            return ci;
        }
示例#40
0
文件: source2.cs 项目: wzchua/docs
 public static void Main()
 {
     System.Reflection.MemberInfo info = typeof(Class1);
     foreach (object attrib in info.GetCustomAttributes(true))
     {
         Console.WriteLine(attrib);
     }
 }
        public virtual MemberSecurityPolicy GetMemberSecurityPolicy(MemberInfo member)
        {
            if (member.GetCustomAttributes(typeof(LuaMemberAttribute), true).Length != 0) {
                return MemberSecurityPolicy.Permit;
            }

            return DefaultPolicy;
        }
示例#42
0
 private static string GetDescription(MemberInfo info)
 {
   DescriptionAttribute descriptionAttribute = Enumerable.FirstOrDefault<object>((IEnumerable<object>) info.GetCustomAttributes(typeof (DescriptionAttribute), false)) as DescriptionAttribute;
   if (descriptionAttribute != null)
     return descriptionAttribute.Description;
   else
     return (string) null;
 }
 /// <summary>
 /// Given a MethodInfo type, returns the attributes (if any) that are of 
 /// the decoratingAttribute parameter's type.
 /// </summary>
 /// <param name="member">MemberInfo instance.</param>
 /// <param name="decoratingAttribute">Attribute of interest.</param>
 /// <param name="inherit">A value indicating whether to look for 
 /// inheriting custom attributes.</param>
 /// <returns>
 /// A collection populated with the Attribute instances.
 /// </returns>
 public static ICollection<Attribute> GetAttributes(MemberInfo member, Type decoratingAttribute, bool inherit)
 {
     if (member == null)
     {
         throw new ArgumentNullException("member");
     }
     return new List<Attribute>(member.GetCustomAttributes(decoratingAttribute, inherit).OfType<Attribute>());
 }
 protected static ReplicationBehavior? TryGetBehaviorFromAttribute(MemberInfo memberOrType)
 {
     CustomReplicationBehaviorAttribute customReplicationBehavior;
     if (memberOrType.GetCustomAttributes<CustomReplicationBehaviorAttribute>()
         .TrySingle(out customReplicationBehavior))
         return customReplicationBehavior.GetReplicationBehavior();
     return null;
 }
        /// <summary>
        /// Common initialization
        /// </summary>
        /// <param name="member">MemberInfo/param>
        /// <param name="dataType">Type of property/field</param>
        private void CommonInit(System.Reflection.MemberInfo member, Type dataType)
        {
            Type = dataType;

            foreach (Attribute attribute in member.GetCustomAttributes(true))
            {
                if (attribute is PartitionKeyAttribute)
                {
                    IsPartitionKey = true;
                }
                else if (attribute is RowKeyAttribute)
                {
                    IsRowKey = true;
                }
                else if (attribute is ETagAttribute)
                {
                    IsETag = true;
                }
                else if (attribute is TimestampAttribute)
                {
                    IsTimestamp = true;
                }
                else if (attribute is TableColumnAttribute tc)
                {
                    // Now the problem is legacy code that may define columns we now have attributes for
                    // as TableColumn() with matching names. So filter those out.

                    switch (tc.ColumnName)
                    {
                    case "ETag":
                        IsETag = true;
                        continue;

                    case "Timestamp":
                        IsTimestamp = true;
                        continue;

                    case "PartitionKey":
                        IsPartitionKey = true;
                        continue;

                    case "RowKey":
                        IsRowKey = true;
                        continue;
                    }

                    // Traditional column
                    TableEntityColumn = tc;
                }
            }

            Type?underlyingType = Nullable.GetUnderlyingType(Type);

            TypeCode  = Type.GetTypeCode(underlyingType ?? Type);
            IsEdmType = EdmTypeConverter.IsEdmCompatibleType(underlyingType ?? Type);

            IsNullableType = (dataType == typeof(string)) || (underlyingType == typeof(string)) || (underlyingType != null);
        }
 public void Test00()
 {
     System.Reflection.MemberInfo info = typeof(Rectangle);
     object[] attributes = info.GetCustomAttributes(true);
     for (int i = 0; i < attributes.Length; i++)
     {
         System.Console.WriteLine(attributes[i]);
     }
 }
        public static T[] GetCustomAttributes <T>(this System.Reflection.MemberInfo type,
                                                  bool inherit = false)
            where T : System.Attribute
        {
            var attributes = type.GetCustomAttributes(typeof(T), inherit);
            var castAttrs  = attributes.Select(attrib => attrib as T).ToArray();

            return(castAttrs);
        }
示例#48
0
        static StackObject *GetCustomAttributes_6(ILIntepreter __intp, StackObject *__esp, IList <object> __mStack, CLRMethod __method, bool isNewObj)
        {
            ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain;
            StackObject *ptr_of_this_method;
            StackObject *__ret = ILIntepreter.Minus(__esp, 3);

            ptr_of_this_method = ILIntepreter.Minus(__esp, 1);
            System.Boolean @inherit = ptr_of_this_method->Value == 1;

            ptr_of_this_method = ILIntepreter.Minus(__esp, 2);
            System.Type @attributeType = (System.Type) typeof(System.Type).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack));
            __intp.Free(ptr_of_this_method);

            ptr_of_this_method = ILIntepreter.Minus(__esp, 3);
            System.Reflection.MemberInfo instance_of_this_method = (System.Reflection.MemberInfo) typeof(System.Reflection.MemberInfo).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack));
            __intp.Free(ptr_of_this_method);

            var result_of_this_method = instance_of_this_method.GetCustomAttributes(true);

            //这里需要对反射进行改造,使其没那么残疾
            List <object> ret = new List <object>();

            foreach (var r in result_of_this_method)
            {
                if (r == null)
                {
                    continue;
                }

                var iltype = r as ILTypeInstance;
                if (iltype != null)
                {
                    //ILR中的type
                    if (iltype.Type.FullName == @attributeType.AssemblyQualifiedName)
                    {
                        ret.Add(r);
                    }
                }
                else
                {
                    //hotfix的type
                    try
                    {
                        if (r.GetType() == attributeType || r.GetType().IsSubclassOf(attributeType))
                        {
                            ret.Add(r);
                        }
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(e);
                        throw;
                    }
                }
            }
            return(ILIntepreter.PushObject(__ret, __mStack, ret.ToArray()));
        }
示例#49
0
 // We accessing attributes through reflection, to query their existence and values.
 // The main reflection methods to query attributes are contained in the System.Reflection.MemberInfo class
 public static void Test_Access_Custom_Attribute()
 {
     System.Reflection.MemberInfo info = typeof(Student);
     object[] attributes = info.GetCustomAttributes(true);
     for (int i = 0; i < attributes.Length; i++)
     {
         System.Console.WriteLine(attributes[i].GetType());
     }
     Console.ReadLine();
 }
示例#50
0
    public static void Main()
    {
        System.Reflection.MemberInfo info = typeof(GrendelToolbarButton);
        object[] attributes = info.GetCustomAttributes(true);

        for (int i = 0; i < attributes.Length; i++)
        {
            System.Console.WriteLine(attributes[i]);
        }
    }
示例#51
0
        public TestAttr_Ref()
        {
            System.Reflection.MemberInfo info = typeof(TestClass);
            attributes = info.GetCustomAttributes(false);
            TestClass testClass = new TestClass();

            testClass.TestInt    = 1;
            testClass.TestString = "test world";
            mytype = typeof(TestClass);
        }
示例#52
0
 public static void  CheckReflection()
 {
     System.Reflection.MemberInfo info = typeof(MyAttrClass);
     object[] attributes = info.GetCustomAttributes(true);
     for (int i = 0; i < attributes.Length; i++)
     {
         System.Console.WriteLine(attributes[i]);
     }
     Console.ReadKey();
 }
示例#53
0
        public static Entity ToCrmEntity(this object entityObject)
        {
            Entity returnValue = null;

            if (entityObject == null)
            {
                return(null);
            }

            System.Reflection.MemberInfo info = entityObject.GetType();

            var schemaAttr = info.GetCustomAttributes(typeof(CrmSchemaName), false).OfType <CrmSchemaName>().FirstOrDefault();

            if (schemaAttr != null)
            {
                string entityName = schemaAttr.SchemaName;
                returnValue = new Entity(entityName);
            }
            else
            {
                return(null);
            }

            PropertyInfo[] properties = entityObject.GetType().GetProperties();

            foreach (PropertyInfo p in properties)
            {
                var attrFiledName     = p.GetCustomAttributes(typeof(CrmFieldName), false).OfType <CrmFieldName>().FirstOrDefault();
                var attrFiledDataType = p.GetCustomAttributes(typeof(CrmFieldDataType), false).OfType <CrmFieldDataType>().FirstOrDefault();

                if (attrFiledName == null || attrFiledDataType == null)
                {
                    continue;
                }

                string      fieldName     = attrFiledName.FieldName;
                CrmDataType fieldDataType = attrFiledDataType.CrmDataType;

                var objectValue = entityObject.GetType().GetProperty(p.Name).GetValue(entityObject, null);

                if (objectValue != null)
                {
                    object crmFieldValue = objectValue.ToCrmType(fieldDataType);

                    if (objectValue.GetType() == typeof(Guid) && (Guid)crmFieldValue == Guid.Empty)
                    {
                        continue;
                    }

                    returnValue[fieldName] = crmFieldValue;
                }
            }

            return(returnValue);
        }
        public static bool ContainsAttributeInterface <T>(this System.Reflection.MemberInfo type, bool inherit = false)
        {
            if (!typeof(T).IsInterface)
            {
                throw new ArgumentException($"{typeof(T).FullName} is not an interface.");
            }
            var attributes = type.GetCustomAttributes(inherit)
                             .Where(attr => attr.GetType().IsSubClassOfGeneric(typeof(T)));

            return(attributes.Any());
        }
        public static TValue GetAttributValue <TAttribute, TValue>(System.Reflection.MemberInfo mi, GetValue_t <TAttribute, TValue> value) where TAttribute : System.Attribute
        {
            TAttribute[] objAtts = (TAttribute[])mi.GetCustomAttributes(typeof(TAttribute), true);
            TAttribute   att     = (objAtts == null || objAtts.Length < 1) ? default(TAttribute) : objAtts[0];

            if (att != null)
            {
                return(value(att));
            }
            return(default(TValue));
        }
 private bool DeserializeThis(System.Reflection.MemberInfo m)
 {
     object[] atts = m.GetCustomAttributes(false);
     foreach (object a in atts)
     {
         if (a.GetType() == typeof(WriteOnlyAttribute) || a.GetType() == typeof(IgnoreAttribute))
         {
             return(false);
         }
     }
     return(true);
 }
示例#57
0
    public static void Main(string[] args)
    {
        System.Reflection.MemberInfo tp = typeof(Attr);
        object[] attrs =
            tp.GetCustomAttributes(typeof(DocumentationAttribute), false);
        // false means don't search ancestor classes and interfaces
        DocumentationAttribute a = (DocumentationAttribute)attrs[0];

        Console.WriteLine("author:    " + a.author);
        Console.WriteLine("date:      " + a.date);
        Console.WriteLine("revision:  " + a.revision);
        Console.WriteLine("docString: " + a.docString);
    }
示例#58
0
        static public int Main()
        {
            System.Reflection.MemberInfo info = typeof(Test);
            object[] attributes = info.GetCustomAttributes(false);
            for (int i = 0; i < attributes.Length; i++)
            {
                System.Console.WriteLine(attributes[i]);
            }
            if (attributes.Length != 1)
            {
                return(1);
            }
            MyAttribute attr = (MyAttribute)attributes [0];

            if (attr.val != "testclass")
            {
                return(2);
            }

            info       = typeof(ITest).GetMethod("get_TestProperty");
            attributes = info.GetCustomAttributes(false);
            for (int i = 0; i < attributes.Length; i++)
            {
                System.Console.WriteLine(attributes[i]);
            }
            if (attributes.Length != 1)
            {
                return(3);
            }

            attr = (MyAttribute)attributes [0];
            if (attr.val != "testifaceproperty")
            {
                return(4);
            }

            return(0);
        }
示例#59
0
        //http://stackoverflow.com/a/13100389/1616645
        public static T GetAttribute <T>(Enum enumValue) where T : Attribute
        {
            T attribute;

            System.Reflection.MemberInfo memberInfo = enumValue.GetType().GetMember(enumValue.ToString())
                                                      .FirstOrDefault();

            if (memberInfo != null)
            {
                attribute = (T)memberInfo.GetCustomAttributes(typeof(T), false).FirstOrDefault();
                return(attribute);
            }
            return(null);
        }
示例#60
0
        /// <summary>
        /// Type や PropertyInfo, FieldInfo から指定された型の属性を取り出して返す
        /// 複数存在した場合には最後の値を返す
        /// 存在しなければ null を返す
        /// </summary>
        /// <typeparam name="AttributeType">取り出したい属性の型</typeparam>
        /// <returns>取り出した属性値</returns>
        public static AttributeType GetAttribute <AttributeType>(this System.Reflection.MemberInfo info)
            where AttributeType : Attribute
        {
            var attrs = info.GetCustomAttributes(typeof(AttributeType), true);

            if (attrs.Length > 0)
            {
                return(attrs.Last() as AttributeType);
            }
            else
            {
                return(null);
            }
        }