/// <summary> /// Create a field base from a fieldinfo object /// Verify the settings against the actual field to ensure it will work. /// </summary> /// <param name="fi">Field Info Object</param> internal FieldBase(FieldInfo fi) { IsNullableType = false; TrimMode = TrimMode.None; FieldOrder = null; InNewLine = false; NextIsOptional = false; IsOptional = false; TrimChars = null; NullValue = null; TrailingArray = false; IsLast = false; IsFirst = false; IsArray = false; CharsToDiscard = 0; FieldInfo = fi; FieldType = FieldInfo.FieldType; if (FieldType.IsArray) FieldTypeInternal = FieldType.GetElementType(); else FieldTypeInternal = FieldType; IsStringField = FieldTypeInternal == typeof(string); object[] attribs = fi.GetCustomAttributes(typeof(FieldConverterAttribute), true); if (attribs.Length > 0) { var conv = (FieldConverterAttribute)attribs[0]; this.Converter = conv.Converter; conv.ValidateTypes(FieldInfo); } else this.Converter = ConvertHelpers.GetDefaultConverter(fi.Name, FieldType); if (this.Converter != null) this.Converter.mDestinationType = FieldTypeInternal; attribs = fi.GetCustomAttributes(typeof(FieldNullValueAttribute), true); if (attribs.Length > 0) { NullValue = ((FieldNullValueAttribute)attribs[0]).NullValue; // mNullValueOnWrite = ((FieldNullValueAttribute) attribs[0]).NullValueOnWrite; if (NullValue != null) { if (!FieldTypeInternal.IsAssignableFrom(NullValue.GetType())) throw new BadUsageException("The NullValue is of type: " + NullValue.GetType().Name + " that is not asignable to the field " + FieldInfo.Name + " of type: " + FieldTypeInternal.Name); } } IsNullableType = FieldTypeInternal.IsValueType && FieldTypeInternal.IsGenericType && FieldTypeInternal.GetGenericTypeDefinition() == typeof(Nullable<>); }
protected static void CheckAttributesCompatibility(FieldInfo attributeContext, HashSet<Type> incompatibleAttributeTypes) { if (attributeContext.GetCustomAttributes().Any(a => incompatibleAttributeTypes.Contains(a.GetType()))) { throw new ConfigurationException( "Incomatible attributes detected: type={0}, field={1}, attributes={2}.", attributeContext.DeclaringType.Name, attributeContext.Name, attributeContext.GetCustomAttributes() .Where(a => a is EcoAttribute) .Select(a => a.GetType().Name) .CommaWhiteSpaceSeparated() ); } }
public static bool MatchesDirection(FieldInfo fieldInfo, eDirection direction) { var attributes = fieldInfo.GetCustomAttributes<DirectionAttribute>(); return attributes != null && attributes.Any(attr => attr.Direction == direction); }
/// <summary> /// 根据枚举值,返回描述字符串 /// 如果多选枚举,返回以","分割的字符串 /// </summary> /// <param name="e"></param> /// <returns></returns> public static string GetAllEnumTitle(Enum e, Enum language = null) { if (e == null) { return(""); } string[] valueArray = e.ToString().Split(ENUM_TITLE_SEPARATOR.ToArray(), StringSplitOptions.RemoveEmptyEntries); Type type = e.GetType(); string ret = ""; foreach (string enumValue in valueArray) { System.Reflection.FieldInfo fi = type.GetField(enumValue.Trim()); if (fi == null) { continue; } EnumTitleAttribute[] attrs = fi.GetCustomAttributes(typeof(EnumTitleAttribute), false) as EnumTitleAttribute[]; if (attrs != null && attrs.Length > 0) { ret += attrs[0].Title + ENUM_TITLE_SEPARATOR; } } return(ret.TrimEnd(ENUM_TITLE_SEPARATOR.ToArray())); }
static public string GetDBAttributes(System.Reflection.FieldInfo info) { string attributes = ""; if (s_Attributes.Count == 0) { Init(); } HashSet <string> xorAttributesName = new HashSet <string>(); foreach (string name in s_AttributesName) { if (attributes.Length > 0) { attributes += " "; } attributes += name; xorAttributesName.Add(name); } foreach (Attribute att in info.GetCustomAttributes(true)) { if (s_Attributes.Contains(att.GetType())) { DBFieldAttribute dbAtt = att as DBFieldAttribute; xorAttributesName.Remove(dbAtt.GetKeyWord()); } } foreach (string name in xorAttributesName) { attributes = attributes.Replace(name, ""); } return(attributes); }
/// <summary> /// 获取每句的描述,获取相关值,用于页面,上绑定,要继承byte,参数indexNum获取枚举的条件 /// </summary> /// <param name="enumType"></param> /// <param name="indexNum"></param> /// <returns></returns> public static List <KeyValuePair <byte, string> > GetEnum(Type enumType, int indexFirst, int indexLast) { var names = System.Enum.GetNames(enumType); if (names != null && names.Length > 0) { List <KeyValuePair <byte, string> > kvList = new List <KeyValuePair <byte, string> >(names.Length); foreach (var item in names) { System.Reflection.FieldInfo finfo = enumType.GetField(item); if ((byte)finfo.GetValue(null) > indexFirst && (byte)finfo.GetValue(null) < indexLast) { object[] enumAttr = finfo.GetCustomAttributes(typeof(System.ComponentModel.DescriptionAttribute), true).ToArray(); if (enumAttr != null && enumAttr.Length > 0) { string description = string.Empty; System.ComponentModel.DescriptionAttribute desc = enumAttr[0] as System.ComponentModel.DescriptionAttribute; if (desc != null) { description = desc.Description; } kvList.Add(new KeyValuePair <byte, string>((byte)finfo.GetValue(null), description)); } } } return(kvList); } return(null); }
public static System.Collections.Generic.Dictionary <string, string> EnumToDictionary(System.Type enumType) { System.Collections.Generic.Dictionary <string, string> dictionary = new System.Collections.Generic.Dictionary <string, string>(); if (!enumType.IsEnum) { return(dictionary); } string[] names = System.Enum.GetNames(enumType); string[] array = names; for (int i = 0; i < array.Length; i++) { string text = array[i]; string text2 = string.Empty; System.Reflection.FieldInfo field = enumType.GetField(text); object[] customAttributes = field.GetCustomAttributes(typeof(DescriptionAttribute), true); if (customAttributes != null && customAttributes.Length > 0) { text2 = ((DescriptionAttribute)customAttributes[0]).Description; } else { text2 = text; } dictionary.Add(text2, System.Convert.ToInt32(System.Enum.Parse(enumType, text2)).ToString()); } return(dictionary); }
public static string GetbyDescription(Type tp, String enumDescription) { string enumValue = null; for (int i = 0; i < tp.GetEnumNames().Length; i++) { System.Reflection.FieldInfo oFieldInfo = tp.GetField(tp.GetEnumNames()[i]); DescriptionAttribute[] attributes = (DescriptionAttribute[])oFieldInfo.GetCustomAttributes(typeof(DescriptionAttribute), false); if (attributes[0].Description == enumDescription) { enumValue = tp.GetEnumNames()[i]; } } MemberInfo[] mi = tp.GetMember(enumValue); if (mi != null && mi.Length > 0) { Key attr = Attribute.GetCustomAttribute(mi[0], typeof(Key)) as Key; if (attr != null) { return(attr.m_name); } } return(null); }
void Start() { //Find tagged public fields: //Find what objects to inspect TODO: maybe add a way not to parse everything (layers, tags) ? MonoBehaviour[] MonoBehaviourArray = UnityEngine.Object.FindObjectsOfType <MonoBehaviour>(); for (int i = 0; i < MonoBehaviourArray.Length; i++) { MonoBehaviour currentBehaviour = MonoBehaviourArray[i]; //Debug.Log ("Introspecting current class :" +currentBehaviour.name+" of type "+currentBehaviour.GetType().Name); System.Reflection.FieldInfo[] FieldArray = currentBehaviour.GetType().GetFields(); for (int j = 0; j < FieldArray.Length; j++) { System.Reflection.FieldInfo currentField = FieldArray[j]; object[] CustomAttributeArray = currentField.GetCustomAttributes(true); if (CustomAttributeArray.Length > 0) { for (int k = 0; k < CustomAttributeArray.Length; k++) { if (CustomAttributeArray[k].GetType() == typeof(DBG_Track)) { //Debug.Log ("\tFound trackable variable @ class :" +currentBehaviour.name+" typeof "+currentBehaviour.GetType().Name +" FieldName = "+ currentField.Name); this.WatchDict[currentField.Name] = new DBG_DataCollector(currentField, currentBehaviour, ((DBG_Track)CustomAttributeArray[k]).VariableColor); } } } } } }
/// <summary> /// 根据枚举获取数据 /// </summary> /// <param name="enumValue"></param> /// <returns></returns> public static string GetEnumDescription(Enum enumValue) { if (_enumValueDic.ContainsKey(enumValue)) { return(_enumValueDic[enumValue]); } if (enumValue == null) { return(""); } string str = enumValue.ToString(); System.Reflection.FieldInfo field = enumValue.GetType().GetField(str); if (field == null) { _enumValueDic.Add(enumValue, str); return(str); } object[] objs = field.GetCustomAttributes(typeof(System.ComponentModel.DescriptionAttribute), false); if (objs == null || objs.Length == 0) { return(str); } System.ComponentModel.DescriptionAttribute da = (System.ComponentModel.DescriptionAttribute)objs[0]; _enumValueDic.Add(enumValue, da.Description); return(da.Description); }
/// <summary> /// Returns the display name of an enum, or the enum name value if the display name is emtpy or null /// </summary> /// <param name="field">The field to show.</param> /// <returns>The firendly name if there is one, or the enum value if not.</returns> private static string FetchDisplayName(FieldInfo field) { string displayName = String.Empty; // load the EnumStringAttributes for the object (there should be 1 and only 1) object[] attributes; attributes = field.GetCustomAttributes(typeof(EnumDisplayNameAttribute), false); EnumDisplayNameAttribute attribute = null; if (attributes.Length > 0) { attribute = attributes[0] as EnumDisplayNameAttribute; } if (attribute != null) { // get the DisplayName property from the attribute displayName = attribute.DisplayName; } else { // if we couldn't get the EnumStringAttribute (or it wasn't set), // then default back to the name of the field displayName = field.Name; } return displayName; }
internal FieldBase(FieldInfo fi) { mFieldInfo = fi; mFieldType = mFieldInfo.FieldType; if (mFieldType.IsArray) mFieldTypeInternal = mFieldType.GetElementType(); else mFieldTypeInternal = mFieldType; mIsStringField = mFieldTypeInternal == strType; object[] attribs = fi.GetCustomAttributes(typeof(FieldConverterAttribute), true); if (attribs.Length > 0) { FieldConverterAttribute conv = (FieldConverterAttribute)attribs[0]; mConvertProvider = conv.Converter; conv.ValidateTypes(mFieldInfo); } else mConvertProvider = ConvertHelpers.GetDefaultConverter(fi.Name, mFieldType); if (mConvertProvider != null) mConvertProvider.mDestinationType = mFieldTypeInternal; attribs = fi.GetCustomAttributes(typeof(FieldNullValueAttribute), true); if (attribs.Length > 0) { mNullValue = ((FieldNullValueAttribute)attribs[0]).NullValue; // mNullValueOnWrite = ((FieldNullValueAttribute) attribs[0]).NullValueOnWrite; if (mNullValue != null) { if (!mFieldTypeInternal.IsAssignableFrom(mNullValue.GetType())) throw new BadUsageException("The NullValue is of type: " + mNullValue.GetType().Name + " that is not asignable to the field " + mFieldInfo.Name + " of type: " + mFieldTypeInternal.Name); } } mIsNullableType = mFieldTypeInternal.IsValueType && mFieldTypeInternal.IsGenericType && mFieldTypeInternal.GetGenericTypeDefinition() == typeof(Nullable<>); }
static public T GetAttribute(System.Reflection.FieldInfo info) { foreach (object attr in info.GetCustomAttributes(typeof(T), false)) { return((T)attr); } return(null); }
static GuidAttribute GetGuidAttribute (FieldInfo fi) { GuidAttribute [] attributes = fi.GetCustomAttributes (typeof (GuidAttribute), false) as GuidAttribute []; if (attributes == null || attributes.Length != 1) return new GuidAttribute (); return attributes [0]; }
/// <summary> /// Returns an enumerated value used by remote Viddler API methods. /// </summary> internal static string GetEnumName(FieldInfo field) { foreach (XmlEnumAttribute attribute in field.GetCustomAttributes(typeof(XmlEnumAttribute), true)) { return attribute.Name; } return null; }
private bool ShouldSkip(FieldInfo fieldInfo) { var customAttributes = fieldInfo.GetCustomAttributes(false); if (HasIgnoreAttribute(customAttributes)) return true; return false; }
private EnumValue(FieldInfo enumField) { Type enumType = enumField.DeclaringType; DescriptionAttribute descriptionAttrib = (DescriptionAttribute)enumField.GetCustomAttributes(typeof(DescriptionAttribute), true).FirstOrDefault(); this.Description = (descriptionAttrib == null) ? enumField.Name : descriptionAttrib.Description; this.Name = enumField.Name; this.Value = Convert.ChangeType(Enum.Parse(enumType, this.Name), enumType); }
public ParameterValue(object instance, FieldInfo field) { ObjectReference = instance; Field = field; foreach (object attribute in field.GetCustomAttributes(typeof(ParameterAttribute), true)) Attribute = attribute as ParameterAttribute; ReadAttribute(); ReadValue(); }
internal String GetFieldTypeFor(FieldInfo fieldInfo) { foreach (Attribute attribute in fieldInfo.GetCustomAttributes(true)) { FieldAttribute fieldAttribute = (FieldAttribute) attribute; return fieldAttribute.Type; } return null; }
public static System.Attribute Exists(System.Type attributeType, System.Reflection.FieldInfo fieldInfo) { System.Attribute[] array = (System.Attribute[])fieldInfo.GetCustomAttributes(attributeType, false); if (array != null && array.Length > 0) { return(array[0]); } return(null); }
private FieldAttribute GetFieldAttribute(FieldInfo f) { var attrs = f.GetCustomAttributes(typeof(FieldAttribute), true); if (attrs == null || attrs.Length == 0) { return new FieldAttribute { Align = 1 }; } return (FieldAttribute) attrs[0]; }
private static void ProcessMember(FieldInfo member) { var attributes = member.GetCustomAttributes(typeof(CompositionFieldAttribute), true); foreach (var att in attributes.OfType<CompositionFieldAttribute>()) { WriteEvents(member, att.MappedEvents); WriteProperties(member, att.MappedProperties); WriteMethods(member, att.MappedMethods); } }
/// <summary> /// Constrói um mapeamento de um campo de um objeto-entidade /// para um parâmetro de banco de dados. /// </summary> /// <param name="campo">Campo a ser mapeado.</param> /// <param name="cmd">Comando do banco de dados.</param> /// <returns>Mapeamento de um campo para um parâmetro.</returns> public static CampoParâmetroBase [] MapearCampoParâmetro(FieldInfo campo, IDbCommand cmd, string prefixo) { DbAtributo atributo; DbAtributo [] atributos; atributos = (DbAtributo []) campo.GetCustomAttributes(typeof(DbAtributo), false); atributo = (DbAtributo) atributos; /* Relacionamentos necessitam de um mapeamento * mais complexo, permitindo múltiplos campos * a partir de um único objeto. */ if (atributo.Relacionamento) { List<CampoObjetoParâmetro> campos = new List<CampoObjetoParâmetro>(); foreach (DbRelacionamento relacionamento in campo.GetCustomAttributes(typeof(DbRelacionamento), false)) campos.Add(new CampoObjetoParâmetro(campo, relacionamento.Campo, relacionamento.Coluna, cmd, prefixo)); return campos.ToArray(); } /* DbFoto deve ser transformado para vetor de bytes * antes da atribuição no parâmetro. */ if (campo.FieldType == typeof(DbFoto) || campo.FieldType.IsSubclassOf(typeof(DbFoto))) return new CampoParâmetroBase [] { new DbFotoParâmetro(campo, cmd, prefixo) }; /* DateTime pode ser nulo no banco de dados, caso * no programa seu valor seja DateTime.MinValue ou * DateTime.MaxValue. */ if (campo.FieldType == typeof(DateTime)) return new CampoParâmetroBase [] { new DateTimeParâmetro(campo, cmd, prefixo) }; if (campo.FieldType.IsDefined(typeof(DbConversão), true)) return new CampoParâmetroBase [] { new CampoParâmetroConvertendo(campo, cmd, prefixo) }; // Mapeamento padrão. return new CampoParâmetroBase [] { new CampoParâmetroSimples(campo, cmd, prefixo) }; }
public FieldPropertyDescriptor(FieldInfo fieldInfo) : base(fieldInfo.Name, new Attribute[0]) { this.fieldInfo = fieldInfo; object[] customAttributes = fieldInfo.GetCustomAttributes(true); Attribute[] attributeArray = new Attribute[customAttributes.Length]; for (int index = 0; index < attributeArray.Length; ++index) attributeArray[index] = (Attribute) customAttributes[index]; this.AttributeArray = attributeArray; }
private static bool ShouldIgnore(FieldInfo fieldInfo, Type type) { object[] attributes = fieldInfo.GetCustomAttributes(true); foreach (Attribute attribute in attributes) { if (attribute.GetType().Equals(type)) return true; } return false; }
private Corruptlet(FieldInfo f, CorruptionType type) { _field = f; var attr = f.GetCustomAttributes().OfType<CorruptableAttribute>().FirstOrDefault(); rangeMin = attr?.MinValue ?? 0f; rangeMax = attr?.MaxValue ?? 1f; rangeMinI = (int)rangeMin; rangeMaxI = (int)rangeMax; _rank = attr?.Level ?? 1; _type = type; }
public ParameterValue(string objectPath, ObjectTree tree, FieldInfo field) { ObjectPath = objectPath; ObjectReference = tree.GetObject(objectPath); FieldPath = objectPath + "." + field.Name; Field = field; foreach (object attribute in field.GetCustomAttributes(typeof(ParameterAttribute), true)) Attribute = attribute as ParameterAttribute; ReadAttribute(); ReadValue(); }
public FieldPropertyDescriptor(FieldInfo fieldInfo) : base(fieldInfo.Name, new Attribute[0]) { this.fieldInfo = fieldInfo; var attributesObject = fieldInfo.GetCustomAttributes(true); var attributes = new Attribute[attributesObject.Length]; for (int i = 0; i < attributes.Length; i++) attributes[i] = (Attribute)attributesObject[i]; this.AttributeArray = attributes; }
/// <summary> /// Go looking for a link attribute. /// </summary> /// <param name="field">The associated field.</param> /// <returns>Returns link or null if none field on specified field.</returns> private static LinkAttribute GetLinkAttribute(FieldInfo field) { var attributes = field.GetCustomAttributes(); foreach (Attribute attribute in attributes) { LinkAttribute link = attribute as LinkAttribute; if (link != null) return link; } return null; }
static bool CheckField (FieldInfo fi, Guid id) { GuidAttribute [] attributes = fi.GetCustomAttributes (typeof (GuidAttribute), false) as GuidAttribute []; if (attributes == null || attributes.Length == 0) return false; foreach (GuidAttribute attr in attributes) if (attr.Guid == id) return true; return false; }
private String GetDisplayStringFor(FieldInfo field, out String displayString, out Object enumValue) { DisplayStringAttribute[] attributes = (DisplayStringAttribute[])field.GetCustomAttributes(typeof(DisplayStringAttribute), false); displayString = GetDisplayStringValue(attributes); enumValue = field.GetValue(null); if (displayString == null) displayString = GetBackupDisplayStringValue(enumValue); return displayString; }
private bool CheckField(FieldInfo f, string fieldName) { // Skip if field is marked as NonSerialized var attrs = f.GetCustomAttributes(typeof(NonSerializedAttribute), true); if (attrs != null && attrs.Length > 0) { return true; } // Otherwise check field type return CheckType(f.FieldType, String.Format("{0}.{1}", fieldName, f.Name)); }
public static string GetDescription(this Enum e) { System.Reflection.FieldInfo oFieldInfo = e.GetType().GetField(e.ToString()); DescriptionAttribute[] attributes = (DescriptionAttribute[])oFieldInfo.GetCustomAttributes(typeof(DescriptionAttribute), false); if (attributes.Length > 0) { return(attributes[0].Description); } else { return(e.ToString()); } }
private static List <PropertyAttribute> GetFieldAttributes(System.Reflection.FieldInfo field) { if (field == null) { return((List <PropertyAttribute>)null); } object[] customAttributes = field.GetCustomAttributes(typeof(PropertyAttribute), true); if (customAttributes != null && customAttributes.Length > 0) { return(new List <PropertyAttribute>((IEnumerable <PropertyAttribute>)((IEnumerable <object>)customAttributes).Select <object, PropertyAttribute>((Func <object, PropertyAttribute>)(e => e as PropertyAttribute)).OrderBy <PropertyAttribute, int>((Func <PropertyAttribute, int>)(e => - e.order)))); } return((List <PropertyAttribute>)null); }
/// <summary> /// 获取枚举的描述 /// </summary> /// <param name="enumValue"></param> /// <returns></returns> public static string GetDescription(this Enum enumValue) { string value = enumValue.ToString(); System.Reflection.FieldInfo field = enumValue.GetType().GetField(value); object[] objs = field.GetCustomAttributes(typeof(System.ComponentModel.DescriptionAttribute), false); if (objs == null || objs.Length == 0) { return(value); } System.ComponentModel.DescriptionAttribute attr = (System.ComponentModel.DescriptionAttribute)objs[0]; return(attr.Description); }
public MemberInfo(object target, SR.FieldInfo info) { _name = null; _target = target; this.FieldInfo = info; this.PropertyInfo = null; _isReadonly = false; var attributes = info.GetCustomAttributes(typeof(InspectorTooltip), true); var attribute = attributes.Length > 0 ? attributes[0] as InspectorTooltip : null; this.Tooltip = attribute != null ? attribute.Tooltip : info.Name; }
private string GetEnumDescription(Enum enumValue) { string str = enumValue.ToString(); System.Reflection.FieldInfo field = enumValue.GetType().GetField(str); object[] objs = field.GetCustomAttributes(typeof(System.ComponentModel.DescriptionAttribute), false); if (objs == null || objs.Length == 0) { return(str); } System.ComponentModel.DescriptionAttribute da = (System.ComponentModel.DescriptionAttribute)objs[0]; return(da.Description); }
public static string GetEnumDescription(string ob, Type enumType) { string str = ob; System.Reflection.FieldInfo field = enumType.GetField(str); object[] objs = field.GetCustomAttributes(typeof(System.ComponentModel.DescriptionAttribute), false); if (objs.Length == 0) { return(str); } var da = (System.ComponentModel.DescriptionAttribute)objs[0]; return(da.Description); }
public static string GetDescriptionByEnum(Enum enumValue) { string value = enumValue.ToString(); System.Reflection.FieldInfo field = enumValue.GetType().GetField(value); object[] objs = field.GetCustomAttributes(typeof(DescriptionAttribute), false); //获取描述属性 if (objs.Length == 0) //当描述属性没有时,直接返回名称 { return(value); } DescriptionAttribute descriptionAttribute = (DescriptionAttribute)objs[0]; return(descriptionAttribute.Description); }
private static IFastGetter CreateFastGetter(FieldInfo field) { var instance = Expression.Parameter(typeof(object)); var getter = Expression.Field(Expression.Convert(instance, field.DeclaringType), field); var cast = Expression.Convert(getter, typeof(object)); return new FastGetter(Expression.Lambda<Func<object, object>>(cast, instance).Compile()) { Attributes = field.GetCustomAttributes().ToArray(), DeclaringType = field.DeclaringType, MemberType = field.FieldType, Name = field.Name }; }
private FieldParameter(object target, FieldInfo field, bool isArray) : base(isArray ? ArrayHelpers.GetUnderlyingType(field.FieldType) : field.FieldType, field.Name) { Target = target; Field = field; Aliases.DisplayName = () => $"<{field.Name}>"; IsArray = isArray; if (!isArray) MaxValues = 1; SetParamInfoFromCustomAttributes(field.GetCustomAttributes()); }
public static string GetDescription(this Enum value) { Reflection.FieldInfo fieldInfo = value .GetType() .GetField(value.GetName()); DescriptionAttribute descriptionAttribute = fieldInfo .GetCustomAttributes(typeof(DescriptionAttribute) , false) .FirstOrDefault() as DescriptionAttribute; return(descriptionAttribute == null?value.GetName() : descriptionAttribute.Description); }
/// <summary> /// Gets the string value of enum /// </summary> /// <param name="value">The Enum value.</param> /// <returns>string value attribute of the Enum value</returns> public static string GetStringValue(this Enum value) { // Get the type Type type = value.GetType(); // Get fieldinfo for this type Reflect.FieldInfo fieldInfo = type.GetField(value.ToString()); // Get the stringvalue attributes StringValueAttribute[] attribs = fieldInfo.GetCustomAttributes( typeof(StringValueAttribute), false) as StringValueAttribute[]; // Return the first if there was a match. return(attribs.Length > 0 ? attribs[0].StringValue : null); }
/// <summary> /// Extrai o nome da coluna. /// </summary> /// <param name="campo">Campo do objeto.</param> /// <returns>Nome da coluna.</returns> protected static string ExtrairNomeColuna(FieldInfo campo) { DbColuna [] atributos; atributos = (DbColuna []) campo.GetCustomAttributes(typeof(DbColuna), false); if (atributos.Length == 0) return campo.Name; else if (atributos.Length == 1) return atributos[0].Coluna; else throw new Exception("Um campo não pode possuir mais de um atributo \"DbColuna\"."); }
public static string GetStringValue(this Enum value) { // Get the type Type type = value.GetType(); // Get fieldinfo for this type System.Reflection.FieldInfo fieldInfo = type.GetTypeInfo().GetDeclaredField(value.ToString()); // Get the stringvalue attributes var attribs = fieldInfo.GetCustomAttributes( typeof(CommandValueAttribute), false) as CommandValueAttribute[]; // Return the first if there was a match. return(attribs.Length > 0 ? attribs[0].CommandValue : null); }
public static string GetDescription(this Enum val) { string name = Enum.GetName(val.GetType(), val); System.Reflection.FieldInfo obj = val.GetType().GetField(name); if (obj != null) { object[] attributes = obj.GetCustomAttributes(typeof(System.ComponentModel.DescriptionAttribute), false); return(attributes.Length > 0 ? ((System.ComponentModel.DescriptionAttribute)attributes[0]).Description : null); } return(null); }
public static bool CanCreateGraphData(ScriptableObject parentObject, FieldInfo fieldInfo, out GraphData graphData) { graphData = null; Type fieldValueType = fieldInfo.FieldType; if (fieldValueType.IsGenericType && (fieldValueType.GetGenericTypeDefinition() == typeof(List<>)) && typeof(ScriptableObject).IsAssignableFrom( fieldValueType.GetGenericArguments()[0])){ object[] attributes = fieldInfo.GetCustomAttributes(false); if (attributes == null || attributes.Length == 0){ return false; } GraphAttribute attribute = attributes .ToList().First((arg) => arg.GetType() == typeof(GraphAttribute)) as GraphAttribute; if (attribute != null){ object fieldValue = fieldInfo.GetValue(parentObject); if (fieldValue == null){ var newList = Activator.CreateInstance(fieldValueType); fieldInfo.SetValue(parentObject, newList); fieldValue = newList; } SerializedObject serializedObject = new SerializedObject(parentObject); graphData = new GraphData(); graphData.ItemBaseType = fieldValueType.GetGenericArguments()[0]; graphData.ItemList = fieldValue as IList; graphData.PropertyName = fieldInfo.Name; graphData.ParentObject = parentObject; graphData.SerializedItemList = serializedObject.FindProperty(fieldInfo.Name); if (string.IsNullOrEmpty(graphData.PropertyName)){ graphData.PropertyName = fieldInfo.Name; } graphData.StartNode = null; if (!string.IsNullOrEmpty(attribute.StartNode)){ graphData.StartNode = serializedObject.FindProperty(attribute.StartNode); if (graphData.StartNode == null){ Debug.LogError("Cant find property with name " + attribute.StartNode +" for this graph"); } else if (false){ //fixme through reflexion get field type graphData.StartNode = null ; Debug.LogError("Start node type is not assignable from graph node type"); } } graphData.SetDefaultStartNodeIfNothingSelected(); return true; } } return false; }
public FldInfo(System.Reflection.FieldInfo fi) { this.fi = fi; this.name = fi.Name; type = fi.FieldType; if (type.IsGenericType) { geneicTypes = type.GetGenericArguments(); } object[] atts = fi.GetCustomAttributes(typeof(JsonFields), true); if (atts.Length > 0) { subFields = new HashSet <string>(((JsonFields)atts[0]).fields); } isFast = typeof(IFastGetSet).IsAssignableFrom(fi.DeclaringType); }
protected override string GeneratePropertiesLabel() { string str = base.GeneratePropertiesLabel(); if (this.IsCompare() && !this.isFirstCondition()) { System.Reflection.FieldInfo fi = this._binary.GetType().GetField(this._binary.ToString()); Attribute[] attributes = (Attribute[])fi.GetCustomAttributes(typeof(EnumMemberDescAttribute), false); if (attributes.Length > 0) { str = ((EnumMemberDescAttribute)attributes[0]).DisplayName + "(" + str + ")"; } } return(str); }
private static SearchCriteria SearchCondition(FieldInfo fieldInfo) { SearchCriteria defaultCriteria = SearchCriteria.ByAutomationId(fieldInfo.Name).AndControlType(fieldInfo.FieldType); SearchCriteria searchCriteria = null; object[] customAttributes = fieldInfo.GetCustomAttributes(false); foreach (Attribute customAttribute in customAttributes) { SearchCriteriaAttribute searchCriteriaAttribute = customAttribute as SearchCriteriaAttribute; if (searchCriteriaAttribute != null) { if (searchCriteria == null) searchCriteria = SearchCriteria.ByControlType(fieldInfo.FieldType); searchCriteriaAttribute.Apply(searchCriteria); } } return searchCriteria ?? defaultCriteria; }
static string GetName(object obj, int lcid) { Type typeDescription = typeof(EnumAttribute); Type enumType = obj.GetType(); if (enumType.IsEnum) { System.Reflection.FieldInfo fieldInfo = enumType.GetField(obj.ToString()); object[] attr = fieldInfo.GetCustomAttributes(typeDescription, false); if (attr.Length > 0) { EnumAttribute attrEnum = attr[0] as EnumAttribute; return(GetNameByCulture(attrEnum, lcid)); } } return(obj.ToString()); }
private static Dictionary <string, string> GetEnumDic(System.Type enumType) { Dictionary <string, string> dictionary = new Dictionary <string, string>(); System.Reflection.FieldInfo[] fields = enumType.GetFields(); System.Reflection.FieldInfo[] array = fields; for (int i = 0; i < array.Length; i++) { System.Reflection.FieldInfo fieldInfo = array[i]; if (fieldInfo.FieldType.IsEnum) { object[] customAttributes = fieldInfo.GetCustomAttributes(typeof(DescriptionAttribute), false); dictionary.Add(fieldInfo.Name, ((DescriptionAttribute)customAttributes[0]).Description); } } return(dictionary); }
public static string GetStringValue(Enum ValueType) { Type oType = ValueType.GetType(); System.Reflection.FieldInfo oFieldInfo = oType.GetField(ValueType.ToString()); StringValueAttribute[] attributes = (StringValueAttribute[])oFieldInfo.GetCustomAttributes(typeof(StringValueAttribute), false); if (attributes.Length > 0) { return(attributes[0].StringValue); } else { return(Convert.DBNull.ToString()); } }
public static T GetCustomAttribute <T>(Enum source, int index) where T : Attribute { Type type = source.GetType(); string fieldName = Enum.GetName(type, source); System.Reflection.FieldInfo info = type.GetField(fieldName); object[] attributes = info.GetCustomAttributes(typeof(T), false); if (attributes != null && attributes.Length > index) { T attribute = attributes[index] as T; if (attribute != null) { return(attribute); } } return(null); }
/// <summary> /// Get the type defined in a TypeRestrictionAttribute attached to the field, otherwise returns the FieldType as defined by the field itself. /// </summary> /// <param name="field"></param> /// <param name="returnNullIfNoTypeRestrictionAttribute">Return null if TypeRestrictionAttribute is not found</param> /// <returns></returns> public static System.Type GetRestrictedFieldType(System.Reflection.FieldInfo field, bool returnNullIfNoTypeRestrictionAttribute = false) { if (field == null) { return(null); } var attrib = field.GetCustomAttributes(typeof(TypeRestrictionAttribute), true).FirstOrDefault() as TypeRestrictionAttribute; if (attrib != null && attrib.InheritsFromType != null) { return(attrib.InheritsFromType); } else { return(returnNullIfNoTypeRestrictionAttribute ? null : field.FieldType); } }
public List <String> getDescriptions(Type EnumType, String enumGroup) { List <String> enumDescriptions = new List <String>(); for (int i = 0; i < EnumType.GetEnumNames().Length; i++) { System.Reflection.FieldInfo oFieldInfo = EnumType.GetField(EnumType.GetEnumNames()[i]); DescriptionAttribute[] attributes = (DescriptionAttribute[])oFieldInfo.GetCustomAttributes(typeof(DescriptionAttribute), false); if (attributes.Length > 0) { if (Group.Get(EnumType, EnumType.GetEnumNames()[i]) == enumGroup) { enumDescriptions.Add(attributes[0].Description); } } } return(enumDescriptions); }
public PocoFeatureAttributeDefinition(FieldInfo fieldInfo) { Ignore = true; AttributeName = fieldInfo.Name; AttributeType = fieldInfo.FieldType; _static = fieldInfo.IsStatic; _field = fieldInfo; _readonly = fieldInfo.IsInitOnly; var att = fieldInfo.GetCustomAttributes(typeof(FeatureAttributeAttribute), true); if (att.Length > 0) { Ignore = false; CorrectByAttribute((FeatureAttributeAttribute)att[0]); } }
public static string GetEnumDisplayName(object obj) { if (obj == null) { return(string.Empty); } string enumName = getEnumName(obj); System.Reflection.FieldInfo fi = obj.GetType().GetField(obj.ToString()); Attribute[] attributes = (Attribute[])fi.GetCustomAttributes(typeof(MemberMetaInfoAttribute), false); if (attributes.Length > 0) { enumName = ((MemberMetaInfoAttribute)attributes[0]).DisplayName; } return(enumName); }
public void Apply(Schema model, SchemaFilterContext context) { if (!string.IsNullOrEmpty(model.Format)) { model.Type = model.Title = model.Format; } return; if (context.SystemType.IsEnum) { IList <object> tmp = new List <object>(); foreach (var val in model.Enum) { object enumValue; bool b; string Description; b = Enum.TryParse(context.SystemType, val.ToString(), out enumValue); if (b) { string str = enumValue.ToString(); System.Reflection.FieldInfo field = enumValue.GetType().GetField(str); object[] objs = field.GetCustomAttributes(typeof(System.ComponentModel.DescriptionAttribute), false); if (objs == null || objs.Length == 0) { Description = val.ToString(); } else { System.ComponentModel.DescriptionAttribute da = (System.ComponentModel.DescriptionAttribute)objs[0]; Description = da.Description; } string ret = string.Format("0x{0:x2}:{1}", (int)enumValue, Description); tmp.Add(ret); } } model.Enum = tmp; } return; throw new NotImplementedException(); }
public GetSetGeneric(FieldInfo info) { Name = info.Name; FieldInfo = info; var customAttrs = info.GetCustomAttributes(typeof(Specialist),true); if(customAttrs.Length>0) { var specialist = (Specialist)customAttrs[0]; Get = (o)=>UnitySerializer.Specialists[specialist.Type].Serialize(info.GetValue(o)); Set = (o,v)=>info.SetValue( o, UnitySerializer.Specialists[specialist.Type].Deserialize(v)); } else { Get = info.GetValue; Set = info.SetValue; } IsStatic = info.IsStatic; CollectionType = FieldInfo.FieldType.GetInterface ("IEnumerable", true) != null; return; }