当前位置: 首页>>代码示例>>C#>>正文


C# PropertyInfo.GetCustomAttributes方法代码示例

本文整理汇总了C#中System.Reflection.PropertyInfo.GetCustomAttributes方法的典型用法代码示例。如果您正苦于以下问题:C# PropertyInfo.GetCustomAttributes方法的具体用法?C# PropertyInfo.GetCustomAttributes怎么用?C# PropertyInfo.GetCustomAttributes使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在System.Reflection.PropertyInfo的用法示例。


在下文中一共展示了PropertyInfo.GetCustomAttributes方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: StringFieldOptions

        public StringFieldOptions(PropertyInfo prop)
        {
            var textFieldAttribute = prop.GetCustomAttributes(typeof(TextFieldAttribute), false).Select(d => d).FirstOrDefault() as TextFieldAttribute;
            var stringLengthAttr = prop.GetCustomAttributes(typeof(StringLengthAttribute), false).Select(d => d).FirstOrDefault() as StringLengthAttribute;
            var richTextAttr = prop.GetCustomAttributes(typeof(RichTextAttribute), false).Select(d => d).FirstOrDefault() as RichTextAttribute;

            if (textFieldAttribute != null)
            {
                Mask = textFieldAttribute.Mask;
                MaskType = textFieldAttribute.MaskType;
                NumberOfCharacters = textFieldAttribute.NumberOfCharacters;
                NumberOfRows = textFieldAttribute.NumberOfRows;
            }

            if (stringLengthAttr == null)
            {
                MinimumLength = 0;
                MinimumLength = 999999999;
            }
            else
            {
                MaximumLength = stringLengthAttr.MaximumLength;
                MinimumLength = stringLengthAttr.MinimumLength;
                ErrorMessage = stringLengthAttr.ErrorMessage;
            }
            if (richTextAttr != null)
            {
                IsRichText = true;
            }
        }
开发者ID:mparsin,项目名称:Elements,代码行数:30,代码来源:StringFieldOptions.cs

示例2: ModelProperty

        public ModelProperty(PropertyInfo propertyInfo)
        {
            PropertyInfo = propertyInfo;
            Name = PropertyInfo.Name;
            Type = PropertyInfo.PropertyType;
            DisplayAttribute = propertyInfo.GetCustomAttributes<DisplayAttribute>().FirstOrDefault();
            DisplayFormatAttribute = propertyInfo.GetCustomAttributes<DisplayFormatAttribute>().FirstOrDefault();
            DefaultValueAttribute = propertyInfo.GetCustomAttributes<DefaultValueAttribute>().FirstOrDefault();
            var attributes = propertyInfo.CustomAttributes;
            //validation
            var maxLengthAttribute = attributes.OfType<MaxLengthAttribute>().FirstOrDefault();//use
            var minLengthAttribute = attributes.OfType<MinLengthAttribute>().FirstOrDefault();//use
            var stringLengthAttribute = attributes.OfType<StringLengthAttribute>().FirstOrDefault();//use validation
            var rangeAttribute = attributes.OfType<RangeAttribute>().FirstOrDefault();//use
            var requiredAttribute = attributes.OfType<RequiredAttribute>().FirstOrDefault();//use validation
            var regularExpressionAttribute = attributes.OfType<RegularExpressionAttribute>().FirstOrDefault();//use
            var dataTypeAttribute = attributes.OfType<DataTypeAttribute>().FirstOrDefault(); //use validation
            var displayAttribute = attributes.OfType<DisplayAttribute>().FirstOrDefault();//use (name,short,description,prompt,
            //display
            var defaultValueAttribute = attributes.OfType<DefaultValueAttribute>().FirstOrDefault(); //use 
            var displayColumnAttribute = attributes.OfType<DisplayColumnAttribute>().FirstOrDefault();//use for select en combo
            var displayFormatAttribute = attributes.OfType<DisplayFormatAttribute>().FirstOrDefault();//use format van date, int etc
            var hiddenInputAttribute = attributes.OfType<HiddenInputAttribute>().FirstOrDefault();//use hide column
            var scaffoldColumnAttribute = attributes.OfType<ScaffoldColumnAttribute>().FirstOrDefault();//use not on form
            var editableAttribute = attributes.OfType<EditableAttribute>().FirstOrDefault();//use readonly
            //skip
            var uiHintAttribute = attributes.OfType<UIHintAttribute>().FirstOrDefault();//skip
            var actionName = attributes.OfType<ActionNameAttribute>().FirstOrDefault(); //skip
            var bindingBehavior = attributes.OfType<BindingBehaviorAttribute>().FirstOrDefault();//skip
            var defaultMemberAttribute = attributes.OfType<DefaultMemberAttribute>().FirstOrDefault();//skip

        }
开发者ID:Anderman,项目名称:Mvc.JQuery.Datatables,代码行数:32,代码来源:ModelProperty.cs

示例3: Create

        public static IFieldOptions Create(PropertyInfo property, IEditableRoot obj)
        {
            if (property == null)
            {
                throw new ArgumentNullException("property");
            }

            var crossRefAttr = property.GetCustomAttributes(typeof(CrossRefFieldAttribute), false).Select(d => d).FirstOrDefault() as CrossRefFieldAttribute;
            if (crossRefAttr == null)
            {
                throw new VeyronException("CrossRef attribute not found on Cross-reference field property");
            }

            var result = new MultiCrossRefFieldOptions { ProcessSystemName = crossRefAttr.ReferenceTableName, FieldName = crossRefAttr.RefFieldName };

            result.LinkVisibility = crossRefAttr.MultiCrAllowLinkUnlink && string.IsNullOrEmpty(crossRefAttr.LinkFieldSystemName);
            result.UnlinkVisibility = crossRefAttr.MultiCrAllowLinkUnlink;
            result.AddNewVisibility = crossRefAttr.MultiCrAllowAddNew;
            result.LinkFieldSystemName = crossRefAttr.LinkFieldSystemName;

            var recentVersionAttr = (from d in property.GetCustomAttributes(typeof(RecentVersionAttribute), true) select d).FirstOrDefault();
            if (recentVersionAttr != null)
            {
                result.AllowRecentVersion = true;
            }

            var deepCopyAttr = (from d in property.GetCustomAttributes(typeof(DeepCopyAttribute), true) select d).FirstOrDefault();
            if (deepCopyAttr != null)
            {
                result.AllowDeepCopy = true;
            }

            return result;
        }
开发者ID:mparsin,项目名称:Elements,代码行数:34,代码来源:MultiCrossRefFieldOptions.cs

示例4: BuildParameterDescriptionMessage

        private static string BuildParameterDescriptionMessage(PropertyInfo propertyInfo, int maxPropertyLength)
        {
            var descriptionAttribute = propertyInfo.GetCustomAttributes<ParameterDescriptionAttribute>().FirstOrDefault();
            var description = descriptionAttribute != null ? descriptionAttribute.Description : string.Empty;

            var exampleAttribute = propertyInfo.GetCustomAttributes<ParameterExampleAttribute>().FirstOrDefault();
            var example = exampleAttribute != null ? exampleAttribute.Example : null;

            var defaultAttribute = propertyInfo.GetCustomAttributes<ParameterDefaultAttribute>().FirstOrDefault();
            var defaultValue = defaultAttribute != null ? defaultAttribute.Value : null;

            var explanation = new StringBuilder();

            if (string.IsNullOrWhiteSpace(description) &&
                string.IsNullOrWhiteSpace(example) &&
                string.IsNullOrWhiteSpace(defaultValue))
            {
                explanation.Append("(No idea. Sorry.)");
            }
            else
            {
                if (!string.IsNullOrWhiteSpace(description))
                    explanation.AppendFormat("{0} ", description);

                if (!string.IsNullOrWhiteSpace(example) || !string.IsNullOrWhiteSpace(defaultValue))
                    explanation.AppendFormat("e.g. '{0}'", example ?? defaultValue);
            }

            var sb = new StringBuilder();
            sb.AppendFormat("{0}", propertyInfo.Name.PadRight(maxPropertyLength));
            sb.Append("\t");
            sb.Append(explanation);
            return sb.ToString();
        }
开发者ID:uglybugger,项目名称:YACLP,代码行数:34,代码来源:UsageMessageBuilder.cs

示例5: TryCreate

        public static IControl TryCreate( object owner, PropertyInfo property )
        {
            var attr = property.GetCustomAttributes( typeof( ArgumentAttribute ), true ).SingleOrDefault();

            if ( attr is ConfigFileArgumentAttribute )
            {
                return new ConfigFileControl( owner, property, (ArgumentAttribute)attr );
            }

            if ( attr != null )
            {
                return new GenericControl( owner, property, (ArgumentAttribute)attr );
            }

            attr = property.GetCustomAttributes( typeof( UserControlAttribute ), true ).SingleOrDefault();

            if ( attr != null )
            {
                var instance = property.GetValue( owner, null );
                if ( instance == null )
                {
                    instance = Activator.CreateInstance( property.PropertyType );
                    property.SetValue( owner, instance, null );
                }

                return new UserControl( instance );
            }

            return null;
        }
开发者ID:JackWangCUMT,项目名称:Plainion,代码行数:30,代码来源:ControlFactory.cs

示例6: PublicProperty_ThatHoldsReferenceType_MustBeTaggedWithNotNullOrCanBeNullAttributes

        public void PublicProperty_ThatHoldsReferenceType_MustBeTaggedWithNotNullOrCanBeNullAttributes(PropertyInfo property)
        {
            bool hasNotNullAttribute = property.GetCustomAttributes(typeof(NotNullAttribute), true).Any();
            bool hasCanBeNullAttribute = property.GetCustomAttributes(typeof(CanBeNullAttribute), true).Any();

            Assume.That(property.DeclaringType != null);
            Assert.That(hasNotNullAttribute || hasCanBeNullAttribute, "Property " + property.Name + " of type " + property.DeclaringType.Name + " must be tagged with [NotNull] or [CanBeNull]");
        }
开发者ID:modulexcite,项目名称:commander,代码行数:8,代码来源:NullableTypeTests.cs

示例7: GenerateRandomStringFromDataAnnotations

        private static string GenerateRandomStringFromDataAnnotations(PropertyInfo propertyInfo, AutoBuilderConfiguration autoBuilderConfiguration)
        {
            var minLength = autoBuilderConfiguration.StringMinLength;
            var maxLength = autoBuilderConfiguration.StringMaxLength;

            var minLengthAttribute = propertyInfo.GetCustomAttributes(typeof(MinLengthAttribute)).FirstOrDefault();
            if (minLengthAttribute != null)
            {
                minLength = ((MinLengthAttribute)minLengthAttribute).Length;
            }

            var maxLengthAttribute = propertyInfo.GetCustomAttributes(typeof(MaxLengthAttribute)).FirstOrDefault();
            if (maxLengthAttribute != null)
            {
                maxLength = ((MaxLengthAttribute)maxLengthAttribute).Length;
            }

            if (minLengthAttribute != null || maxLengthAttribute != null)
            {
                {
                    return NAuto.GetRandomString(
                        minLength,
                        maxLength,
                        autoBuilderConfiguration.DefaultStringCharacterSetType,
                        autoBuilderConfiguration.DefaultStringSpaces,
                        autoBuilderConfiguration.DefaultStringCasing,
                        autoBuilderConfiguration.DefaultLanguage);
                }
            }

            var stringLengthAttribute = propertyInfo.GetCustomAttributes(typeof(StringLengthAttribute)).FirstOrDefault();

            if (stringLengthAttribute != null)
            {
                var minStringLength = ((StringLengthAttribute)stringLengthAttribute).MinimumLength;
                var maxStringLength = ((StringLengthAttribute)stringLengthAttribute).MaximumLength;

                if (maxStringLength == 0)
                {
                    maxStringLength = minStringLength + 50;
                }

                if (maxStringLength < minStringLength)
                {
                    throw new ArgumentException("Property " + propertyInfo.Name + ": the minimum string length cannot be greater than the maximum string length...");
                }

                return NAuto.GetRandomString(
                        minStringLength,
                        maxStringLength,
                        autoBuilderConfiguration.DefaultStringCharacterSetType,
                        autoBuilderConfiguration.DefaultStringSpaces,
                        autoBuilderConfiguration.DefaultStringCasing,
                        autoBuilderConfiguration.DefaultLanguage);
            }

            return null;
        }
开发者ID:RichardSlater,项目名称:NAuto,代码行数:58,代码来源:DataAnnotationConventionMapper.cs

示例8: ReflectableTaskPropertyInfo

 /// <summary>
 /// Initializes a new instance of the <see cref="ReflectableTaskPropertyInfo"/> class.
 /// </summary>
 /// <param name="propertyInfo">The PropertyInfo used to discover this task property.</param>
 internal ReflectableTaskPropertyInfo(PropertyInfo propertyInfo)
     : base(
     propertyInfo.Name,
     propertyInfo.PropertyType,
     propertyInfo.GetCustomAttributes(typeof(OutputAttribute), true).Length > 0,
     propertyInfo.GetCustomAttributes(typeof(RequiredAttribute), true).Length > 0)
 {
     _propertyInfo = propertyInfo;
 }
开发者ID:cameron314,项目名称:msbuild,代码行数:13,代码来源:ReflectableTaskPropertyInfo.cs

示例9: GetPersistentAttribute

 private static PersistentPropertyAttribute GetPersistentAttribute(PropertyInfo p)
 {
     if (p.GetCustomAttributes(typeof(PersistentPropertyAttribute), false).Length > 0)
     {
         return (PersistentPropertyAttribute)p.GetCustomAttributes(typeof(PersistentPropertyAttribute), false)[0];
     }
     
     return null;
 }
开发者ID:n3rus,项目名称:mooege,代码行数:9,代码来源:PersistenceManager.cs

示例10: FromProperty

        public static ColumnInfo FromProperty(PropertyInfo propertyInfo,bool explicitColumn=false)
        {
            var colAttrs = propertyInfo.GetCustomAttributes(typeof(ColumnAttribute), true);
            var keyAttrs= propertyInfo.GetCustomAttributes(typeof(KeyAttribute), true);
            if (explicitColumn)
            {
                if (colAttrs.Length == 0&& keyAttrs.Length==0)
                    return null;
            }
            else
            {
                if (propertyInfo.GetCustomAttributes(typeof(IgnoreAttribute), true).Length != 0)
                    return null;
            }

            var ci = new ColumnInfo();

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

                ci.Name = colattr.Name == null ? propertyInfo.Name : colattr.Name;
                ci.ForceToUtc = colattr.ForceToUtc;
                ci.IsPrimaryKey = false;
                if ((colattr as ResultAttribute) != null)
                    ci.IsResult = true;
            }
            else
            {
                if (keyAttrs.Length > 0)
                {
                    var keyAttr = (KeyAttribute)keyAttrs[0];
                    ci.Name = keyAttr.Name == null ? propertyInfo.Name : keyAttr.Name;
                    ci.IsPrimaryKey = true;
                    ci.PropInfo = propertyInfo;
                    ci.ForceToUtc = false;
                    ci.IsResult = false;
                }
                else
                {
                    ci.Name = propertyInfo.Name;
                    ci.ForceToUtc = false;
                    ci.IsResult = false;
                    ci.IsPrimaryKey = false;
                }
            }
            return ci;
        }
开发者ID:luohuazhiyu,项目名称:GrapeDapper,代码行数:49,代码来源:ColumnInfo.cs

示例11: FromProperty

        public static Specification FromProperty(PropertyInfo property)
        {
            System.Collections.Generic.List<string> enumList = new System.Collections.Generic.List<string>();
            if (property.PropertyType.IsEnum)
            {
                enumList.AddRange(Enum.GetNames(property.PropertyType));
            }
            
            var attrs = property.GetCustomAttributes(true);
            var oa = attrs.OfType<OptionAttribute>();
            if (oa.Count() == 1)
            {
                var spec = OptionSpecification.FromAttribute(oa.Single(), property.PropertyType, enumList);
                if (spec.ShortName.Length == 0 && spec.LongName.Length == 0)
                {
                    return spec.WithLongName(property.Name.ToLowerInvariant(), enumList);
                }
                return spec;
            }

            var va = attrs.OfType<ValueAttribute>();
            if (va.Count() == 1)
            {
                return ValueSpecification.FromAttribute(va.Single(), property.PropertyType);
            }

            throw new InvalidOperationException();
        }
开发者ID:cosmo0,项目名称:commandline,代码行数:28,代码来源:Specification.cs

示例12: Validate

        /// <summary>
        /// Checks if value is within the range specified on property.
        /// If property is not decorated with a RangeAttribute, a range of 1 up to int.MaxValue is used.
        /// </summary>
        /// <param name="property">
        /// The PropertyInfo which should be set with value.
        /// </param>
        /// <param name="value">
        /// The value to validate.
        /// </param>
        /// <param name="description">
        /// A description of the error if value is not valid, or an empty string.
        /// </param>
        /// <returns>
        /// true if value is valid; otherwise, false.
        /// </returns>
        public static bool Validate(PropertyInfo property, int value, out string description)
        {
            if (RangeAttribute.IsDefinedOn(property))
            {
                var attribute = (RangeAttribute) property.GetCustomAttributes(typeof(RangeAttribute), false)[0];

                if (value < attribute.MinValue)
                {
                    description = string.Format("Value should be greater than {0}.", attribute.MinValue);

                    return false;
                }

                if (value > attribute.MaxValue)
                {
                    description = string.Format("Value should be less than {0}.", attribute.MaxValue);

                    return false;
                }
            }
            else
            {
                // No RangeAttribute set; a default range of 1..Int32.MaxValue (the default of RangeAttribute) is used.
                if (value < 1)
                {
                    description = "Value should be greater than 0.";

                    return false;
                }
            }

            description = string.Empty;

            return true;
        }
开发者ID:rh,项目名称:mix,代码行数:51,代码来源:RangeValidator.cs

示例13: GetEnumValues

        private static IEnumerable<object> GetEnumValues(Type enumType, PropertyInfo property)
        {
            var converterAttribute =
                property.GetCustomAttributes(false).OfType<JsonConverterAttribute>().FirstOrDefault();

            if (converterAttribute != null)
            {
                var converter = (JsonConverter) Activator.CreateInstance(converterAttribute.ConverterType);
                if (converter.CanConvert(enumType))
                {
                    foreach (var value in Enum.GetValues(enumType))
                    {
                        using (var stringWriter = new StringWriter())
                        {
                            using (var jsonWriter = new JsonTextWriter(stringWriter))
                                converter.WriteJson(jsonWriter, value, new JsonSerializer());

                            yield return stringWriter.ToString().Replace("\"", String.Empty);
                            ;
                        }
                    }
                }
            }
            else
            {
                foreach (var name in Enum.GetNames(enumType))
                    yield return name;
            }
        }
开发者ID:ehvattum,项目名称:raven-csharp,代码行数:29,代码来源:SchemaHelper.cs

示例14: CreateMBeanAttributeInfo

 public MBeanAttributeInfo CreateMBeanAttributeInfo(PropertyInfo info)
 {
     Descriptor descriptor = new Descriptor();
      OpenType openType = OpenType.CreateOpenType(info.PropertyType);
      descriptor.SetField(OpenTypeDescriptor.Field, openType);
      object[] tmp = info.GetCustomAttributes(typeof(OpenMBeanAttributeAttribute), false);
      if (tmp.Length > 0)
      {
     OpenMBeanAttributeAttribute attr = (OpenMBeanAttributeAttribute)tmp[0];
     if (attr.LegalValues != null && (attr.MinValue != null || attr.MaxValue != null))
     {
        throw new OpenDataException("Cannot specify both min/max values and legal values.");
     }
     IComparable defaultValue = (IComparable)attr.DefaultValue;
     OpenInfoUtils.ValidateDefaultValue(openType, defaultValue);
     descriptor.SetField(DefaultValueDescriptor.Field, defaultValue);
     if (attr.LegalValues != null)
     {
        OpenInfoUtils.ValidateLegalValues(openType, attr.LegalValues);
        descriptor.SetField(LegalValuesDescriptor.Field, attr.LegalValues);
     }
     else
     {
        OpenInfoUtils.ValidateMinMaxValue(openType, defaultValue, attr.MinValue, attr.MaxValue);
        descriptor.SetField(MinValueDescriptor.Field, attr.MinValue);
        descriptor.SetField(MaxValueDescriptor.Field, attr.MaxValue);
     }
      }
      return new MBeanAttributeInfo(info.Name, InfoUtils.GetDescrition(info, info, "MBean attribute"), openType.Representation.AssemblyQualifiedName,
     info.CanRead, info.CanWrite, descriptor);
 }
开发者ID:SzymonPobiega,项目名称:NetMX,代码行数:31,代码来源:OpenMBeanBeanInfoFactory.cs

示例15: GetChildItem

    private static ExplorerItem GetChildItem(ILookup<Type, ExplorerItem> elementTypeLookup, PropertyInfo childProp) {
      // If the property's type is in our list of entities, then it's a Many:1 (or 1:1) reference.
      // We'll assume it's a Many:1 (we can't reliably identify 1:1s purely from reflection).
      if (elementTypeLookup.Contains(childProp.PropertyType))
        return new ExplorerItem(childProp.Name, ExplorerItemKind.ReferenceLink, ExplorerIcon.ManyToOne) {
          HyperlinkTarget = elementTypeLookup[childProp.PropertyType].First(),
          // FormatTypeName is a helper method that returns a nicely formatted type name.
          ToolTipText = DataContextDriver.FormatTypeName(childProp.PropertyType, true)
        };

      // Is the property's type a collection of entities?
      Type ienumerableOfT = childProp.PropertyType.GetInterface("System.Collections.Generic.IEnumerable`1");
      if (ienumerableOfT != null) {
        Type elementType = ienumerableOfT.GetGenericArguments()[0];
        if (elementTypeLookup.Contains(elementType))
          return new ExplorerItem(childProp.Name, ExplorerItemKind.CollectionLink, ExplorerIcon.OneToMany) {
            HyperlinkTarget = elementTypeLookup[elementType].First(),
            ToolTipText = DataContextDriver.FormatTypeName(elementType, true)
          };
      }

      // Ordinary property:
      var isKey = childProp.GetCustomAttributes(false).Any(a => a.GetType().Name == "KeyAttribute");
      return new ExplorerItem(childProp.Name + " (" + DataContextDriver.FormatTypeName(childProp.PropertyType, false) + ")",
        ExplorerItemKind.Property, isKey ? ExplorerIcon.Key : ExplorerIcon.Column) { DragText = childProp.Name };
    }
开发者ID:IdeaBlade,项目名称:DevForce.Utilities,代码行数:26,代码来源:SchemaHelper.cs


注:本文中的System.Reflection.PropertyInfo.GetCustomAttributes方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。