private static MemberInfo[] GetSerializableMembers2(Type type) { // get the list of all fields FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance); int countProper = 0; for (int i = 0; i < fields.Length; i++) { if ((fields[i].Attributes & FieldAttributes.NotSerialized) == FieldAttributes.NotSerialized) continue; countProper++; } if (countProper != fields.Length) { FieldInfo[] properFields = new FieldInfo[countProper]; countProper = 0; for (int i = 0; i < fields.Length; i++) { if ((fields[i].Attributes & FieldAttributes.NotSerialized) == FieldAttributes.NotSerialized) continue; properFields[countProper] = fields[i]; countProper++; } return properFields; } else return fields; }
/// <summary> /// 动态成员分组 /// </summary> /// <param name="type">目标类型</param> public memberGroup(Type type) { PublicFields = type.GetFields(BindingFlags.Public | BindingFlags.Instance); NonPublicFields = type.GetFields(BindingFlags.NonPublic | BindingFlags.Instance).getFindArray(value => value.Name[0] != '<'); PublicProperties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance); NonPublicProperties = type.GetProperties(BindingFlags.NonPublic | BindingFlags.Instance); }
internal static List<Field> GetRuntimeSerializableFields(Type _objectType, RuntimeSerializableAttribute _runtimeSerializableAttr) { List<Field> _serializableFields = null; lock (typeMemberInfoCache) { // If cached value doesnt exist, then use Reflection to get list of RuntimeSerializable fields if (!typeMemberInfoCache.TryGetValue(_objectType, out _serializableFields)) { bool _serializeAllPublicFields = false; bool _serializeAllNonPublicFields = false; if (_runtimeSerializableAttr != null) { _serializeAllPublicFields = _runtimeSerializableAttr.SerializeAllPublicVariables; _serializeAllNonPublicFields = _runtimeSerializableAttr.SerializeAllNonPublicVariables; } // Using reflection fetch all the fields FieldInfo[] _publicFields = _objectType.GetFields(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly | BindingFlags.Static); FieldInfo[] _nonPublicFields = _objectType.GetFields(BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly | BindingFlags.Static); // List holds both public and non-public fields which needs to be serialised _serializableFields = new List<Field>(_publicFields.Length + _nonPublicFields.Length); FilterOutNonSerializableFields(_publicFields, _serializeAllPublicFields, ref _serializableFields); FilterOutNonSerializableFields(_nonPublicFields, _serializeAllNonPublicFields, ref _serializableFields); // Cache member typeMemberInfoCache[_objectType] = _serializableFields; } } return _serializableFields; }
public static void EmptyAndUnknownMatches(Type svo, SingleValueObjectAttribute attr) { var emptyValue = svo.GetFields(BindingFlags.Static | BindingFlags.Public).SingleOrDefault(field => field.Name == "Empty" && field.IsInitOnly && field.FieldType == svo); var unknownValue = svo.GetFields(BindingFlags.Static | BindingFlags.Public).SingleOrDefault(field => field.Name == "Unknown" && field.IsInitOnly && field.FieldType == svo); var isEmptyMethod = svo.GetMethods(BindingFlags.Instance | BindingFlags.Public).SingleOrDefault(method => method.Name == "IsEmpty" && method.GetParameters().Length == 0 && method.ReturnType == typeof(Boolean)); var isUnknownMethod = svo.GetMethods(BindingFlags.Instance | BindingFlags.Public).SingleOrDefault(method => method.Name == "IsUnknown" && method.GetParameters().Length == 0 && method.ReturnType == typeof(Boolean)); var isEmptyOrUnknownMethod = svo.GetMethods(BindingFlags.Instance | BindingFlags.Public).SingleOrDefault(method => method.Name == "IsEmptyOrUnknown" && method.GetParameters().Length == 0 && method.ReturnType == typeof(Boolean)); if (attr.StaticOptions.HasFlag(SingleValueStaticOptions.HasEmptyValue)) { Assert.IsNotNull(emptyValue, "{0} should contain a static read-only Empty field.", svo); Assert.IsNotNull(isEmptyMethod, "{0} should contain a IsEmpty method.", svo); } else { Assert.IsNull(emptyValue, "{0} should not contain a static read-only Empty field.", svo); Assert.IsNull(isEmptyMethod, "{0} should not contain a IsEmpty method.", svo); } if (attr.StaticOptions.HasFlag(SingleValueStaticOptions.HasUnknownValue)) { Assert.IsNotNull(unknownValue, "{0} should contain a static read-only Unknown field.", svo); Assert.IsNotNull(isUnknownMethod, "{0} should contain a IsUnknown method.", svo); } else { Assert.IsNull(unknownValue, "{0} should not contain a static read-only Unknown field.", svo); Assert.IsNull(isUnknownMethod, "{0} should not contain a IsUnknown method.", svo); } if (attr.StaticOptions.HasFlag(SingleValueStaticOptions.HasEmptyValue) && attr.StaticOptions.HasFlag(SingleValueStaticOptions.HasUnknownValue)) { Assert.IsNotNull(isEmptyOrUnknownMethod, "{0} should contain a IsEmptyOrUnknown method.", svo); } else { Assert.IsNull(isEmptyOrUnknownMethod, "{0} should not contain a IsEmptyOrUnknown method.", svo); } }
static void ListFields(Type t) { Console.WriteLine("***** Fields *****"); FieldInfo[] fi = t.GetFields(); var fieldNames = from f in t.GetFields() select f.Name; foreach (var name in fieldNames) Console.WriteLine("->{0}", name); Console.WriteLine(); }
/// <summary> /// Initializes a new instance of the <see cref="ObjectDescriptor" /> class. /// </summary> /// <param name="attributeRegistry">The attribute registry.</param> /// <param name="type">The type.</param> /// <param name="namingConvention">The naming convention.</param> /// <exception cref="System.ArgumentException">Type [{0}] is not a primitive</exception> public PrimitiveDescriptor(IAttributeRegistry attributeRegistry, Type type, IMemberNamingConvention namingConvention) : base(attributeRegistry, type, false, namingConvention) { if (!IsPrimitive(type)) throw new ArgumentException("Type [{0}] is not a primitive"); // Handle remap for enum items if (type.IsEnum) { foreach (var member in type.GetFields(BindingFlags.Public|BindingFlags.Static)) { var attributes = attributeRegistry.GetAttributes(member); foreach (var attribute in attributes) { var yamlRemap = attribute as YamlRemapAttribute; if (yamlRemap != null) { if (enumRemap == null) { enumRemap = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase); } enumRemap[yamlRemap.Name] = member.GetValue(null); } } } } }
private static string GenerateCSharpXmlDeserializer(Type classType, string currentName, string xmlPath) { xmlPath = xmlPath.Trim('/'); var sb = new StringBuilder(); var properties = classType.GetProperties(); if (properties.Length == 0) { var fields = classType.GetFields(); foreach (var fieldInfo in fields) { if (fieldInfo.FieldType.Name == "String") { sb.AppendLine("\t\t\tsubNode = node.SelectSingleNode(\"" + fieldInfo.Name + "\");"); sb.AppendLine("\t\t\tif (subNode != null)"); sb.AppendLine("\t\t\t\t" + currentName + "." + fieldInfo.Name + " = subNode.InnerText;"); } } foreach (var fieldInfo in fields) { if (fieldInfo.FieldType.Name != "String" && fieldInfo.FieldType.FullName.Contains("LanguageStructure")) { sb.AppendLine(); sb.AppendLine("\t\t\t" + currentName + "." + fieldInfo.Name + " = new " + fieldInfo.FieldType.FullName.Replace("+", ".") + "();"); sb.AppendLine("\t\t\tnode = doc.DocumentElement.SelectSingleNode(\"" + fieldInfo.Name + "\");"); sb.AppendLine("\t\t\tif (node != null)"); sb.AppendLine("\t\t\t{"); sb.AppendLine(GenerateCSharpXmlDeserializer(fieldInfo.FieldType, currentName + "." + fieldInfo.Name, xmlPath + "/" + fieldInfo.Name + "/")); sb.AppendLine("\t\t\t}"); } } } else { foreach (var prp in properties) { if (prp.PropertyType.Name == "String") { sb.AppendLine("\t\t\tsubNode = node.SelectSingleNode(\"" + prp.Name + "\");"); sb.AppendLine("\t\t\tif (subNode != null)"); sb.AppendLine("\t\t\t\t" + currentName + "." + prp.Name + " = subNode.InnerText;"); } } foreach (var prp in properties) { if (prp.PropertyType.Name != "String" && prp.PropertyType.FullName.Contains("LanguageStructure")) { sb.AppendLine(); sb.AppendLine("\t\t\t" + currentName + "." + prp.Name + " = new " + prp.PropertyType.FullName.Replace("+", ".") + "();"); sb.AppendLine("\t\t\tnode = doc.DocumentElement.SelectSingleNode(\"" + xmlPath + "/" + prp.Name + "\");"); sb.AppendLine("\t\t\tif (node != null)"); sb.AppendLine("\t\t\t{"); sb.AppendLine(GenerateCSharpXmlDeserializer(prp.PropertyType, currentName + "." + prp.Name, xmlPath + "/" + prp.Name + "/")); sb.AppendLine("\t\t\t}"); } } } return sb.ToString(); }
public SqlTextBuilder(object obj) { this.obj = obj; this.t = obj.GetType(); this.fInfos = t.GetFields(); this.sqlBuilder = new StringBuilder(); }
/// <summary> /// Verify the expectations on a message type. /// </summary> /// <param name="type">The message type to assert on.</param> private static void TestType(Type type) { // get the fields of the type FieldInfo[] fields = type.GetFields(); // all fields must be public readonly Assert.IsTrue(fields.All(f => f.IsPublic && f.IsInitOnly), "All fields must be marked public readonly. Not conforming: {0}", fields.Where(f => !(f.IsPublic && f.IsInitOnly)).Select(f => f.Name).ToArray()); // get the constructors of the type ConstructorInfo[] constructors = type.GetConstructors(); // the type must have exactly one constructor Assert.Count(1, constructors, "The message type has {0} constructors and must have exactly 1", constructors.Count()); ConstructorInfo constructor = constructors.Single(); // get the parameters of the constructor ParameterInfo[] parameters = constructor.GetParameters(); // the parameter count must be exactly as the field count Assert.Count(fields.Count(), parameters, "The constructor parameter {0} count must be the same as the field count {1} .", parameters.Count(), fields.Count()); // get the names of the fields IEnumerable<string> fieldNames = fields.Select(f => f.Name.ToLowerInvariant()); // get the names of the constructor parameters IEnumerable<string> paramNames = parameters.Select(p => p.Name.ToLowerInvariant()); // assert they are the same Assert.AreElementsEqualIgnoringOrder(fieldNames, paramNames); }
public ModelDescription Generate(Type modelType, ModelDescriptionGenerator generator) { var enumDescription = new EnumTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = generator.CreateDefaultDocumentation(modelType) }; var hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; foreach (var field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static)) { if (!ModelDescriptionGenerator.ShouldDisplayMember(field, hasDataContractAttribute)) continue; var enumValue = new EnumValueDescription { Name = field.Name, Value = field.GetRawConstantValue().ToString() }; if (generator.DocumentationProvider != null) { enumValue.Documentation = generator.DocumentationProvider.GetDocumentation(field); } enumDescription.Values.Add(enumValue); } generator.GeneratedModels.Add(enumDescription.Name, enumDescription); return enumDescription; }
public static object FromScalars(Type t, StringReader r, ContinueAtDelegate c) { var n = Activator.CreateInstance(t); var f = t.GetFields(); var x = r.ReadLine(); while (x != null) { if (x.StartsWith(Indent)) { var i = x.IndexOf(Assignment); var FieldName = x.Substring(Indent.Length, i - Indent.Length); var FieldValue = x.Substring(i + Assignment.Length); t.SetFieldValue(FieldName, n, FieldValue); x = r.ReadLine(); } else { c(x); x = null; } } return n; }
public static void Load(Type T, string DllName) { AppDomain Cur = AppDomain.CurrentDomain; AssemblyName AsmName = new AssemblyName("RuntimePInvokeAsm"); AssemblyBuilder AsmBuilder = Cur.DefineDynamicAssembly(AsmName, AssemblyBuilderAccess.RunAndSave); ModuleBuilder ModBuild = AsmBuilder.DefineDynamicModule(AsmName.Name); TypeBuilder TBuild = ModBuild.DefineType("RuntimePInvoke_" + T.Name, TypeAttributes.Public); MethodAttributes MAttr = MethodAttributes.Public | MethodAttributes.Static | MethodAttributes.PinvokeImpl; RuntimeDllImportAttribute Attr; FieldInfo[] Fields = T.GetFields(BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); for (int i = 0; i < Fields.Length; i++) if (typeof(Delegate).IsAssignableFrom(Fields[i].FieldType) && (Attr = Fields[i].GetCustomAttribute<RuntimeDllImportAttribute>()) != null) { MethodInfo MInf = Fields[i].FieldType.GetMethod("Invoke"); string EntryPoint = Attr.EntryPoint != null ? Attr.EntryPoint : Fields[i].Name; MethodBuilder MB = TBuild.DefinePInvokeMethod(EntryPoint, DllName, MAttr, CallingConventions.Standard, MInf.ReturnType, GetParamTypes(MInf), Attr.CallingConvention, Attr.CharSet); if (Attr.PreserveSig) MB.SetImplementationFlags(MB.GetMethodImplementationFlags() | MethodImplAttributes.PreserveSig); } Type RPInv = TBuild.CreateType(); for (int i = 0; i < Fields.Length; i++) if (typeof(Delegate).IsAssignableFrom(Fields[i].FieldType) && (Attr = Fields[i].GetCustomAttribute<RuntimeDllImportAttribute>()) != null) { string EntryPoint = Attr.EntryPoint != null ? Attr.EntryPoint : Fields[i].Name; Fields[i].SetValue(null, Delegate.CreateDelegate(Fields[i].FieldType, RPInv.GetMethod(EntryPoint, GetParamTypes(Fields[i].FieldType.GetMethod("Invoke"))), true)); } }
public EnumDescriptor(Type type) { _type = type; _enum2name = new Dictionary<object, string>(); _name2enum = new Dictionary<string, object>(); var names = Enum.GetNames(type); foreach (string name in names) { #if NET40 var member = type.GetFields().Single(x => x.Name == name); #elif !PCL var member = type.GetTypeInfo().GetRuntimeFields().Single((x) => x.Name == name); #else var member = type.GetTypeInfo().GetDeclaredField(name); #endif var value = Enum.Parse(type, name); var realName = name; #if NET40 var attr = (EnumValueAttribute)member.GetCustomAttributes(typeof(EnumValueAttribute), false).FirstOrDefault(); #else var attr = member.GetCustomAttribute<EnumValueAttribute>(); #endif if (attr != null) realName = attr.Value; _enum2name[value] = realName; _name2enum[realName] = value; } }
public IEnumerable<MemberInfo> FindMembers( Type type ) { foreach (var fieldInfo in type.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly)) { if (fieldInfo.IsInitOnly || fieldInfo.IsLiteral) { // we can't write continue; } yield return fieldInfo; } foreach (var propertyInfo in type.GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly)) { if (!propertyInfo.CanRead || (!propertyInfo.CanWrite && type.Namespace != null)) { // we can't write or it is anonymous... continue; } // skip indexers if (propertyInfo.GetIndexParameters().Length != 0) { continue; } yield return propertyInfo; } }
public IEnumerable<MemberInfo> FindMembers( Type type ) { foreach (var fieldInfo in type.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly)) { if (fieldInfo.IsInitOnly || fieldInfo.IsLiteral) { // we can't write continue; } yield return fieldInfo; } foreach (var propertyInfo in type.GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly)) { if (!propertyInfo.CanRead || (!propertyInfo.CanWrite && type.Namespace != null)) { // we can't write or it is anonymous... continue; } // skip indexers if (propertyInfo.GetIndexParameters().Length != 0) { continue; } // skip overridden properties (they are already included by the base class) var getMethodInfo = propertyInfo.GetGetMethod(true); if (getMethodInfo.IsVirtual && getMethodInfo.GetBaseDefinition().DeclaringType != type) { continue; } yield return propertyInfo; } }
private static object[] GetValues( Type enumType ) { List<object> values = new List<object>(); if( enumType != null ) { var fields = enumType.GetFields().Where( x => x.IsLiteral ); foreach( FieldInfo field in fields ) { // Get array of BrowsableAttribute attributes object[] attrs = field.GetCustomAttributes( typeof( BrowsableAttribute ), false ); if( attrs.Length == 1 ) { // If attribute exists and its value is false continue to the next field... BrowsableAttribute brAttr = ( BrowsableAttribute )attrs[ 0 ]; if( brAttr.Browsable == false ) continue; } values.Add( field.GetValue( enumType ) ); } } return values.ToArray(); }
/// <summary> /// Construct an ArrayBufferObjectInterleaved specifying its item layout on CPU side. /// </summary> /// <param name="arrayItemType"> /// A <see cref="Type"/> describing the type of the array item. /// </param> /// <param name="hint"> /// An <see cref="BufferObjectHint"/> that specify the data buffer usage hints. /// </param> public ArrayBufferObjectInterleaved(Type arrayItemType, BufferObjectHint hint) : base(arrayItemType, hint) { // Get fields for defining array item definition FieldInfo[] arrayItemTypeFields = arrayItemType.GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance); if (arrayItemTypeFields.Length == 0) throw new ArgumentException("no public fields", "arrayItemType"); // Determine array sections stride int structStride = Marshal.SizeOf(arrayItemType); for (int i = 0; i < arrayItemTypeFields.Length; i++) { FieldInfo arrayItemTypeField = arrayItemTypeFields[i]; ArraySection arraySection = new ArraySection(this, arrayItemTypeField.FieldType); // Determine array section offset arraySection.ItemOffset = Marshal.OffsetOf(arrayItemType, arrayItemTypeField.Name); // Determine array section stride arraySection.ItemStride = new IntPtr(structStride); // Mission Normalized property management: add attributes? arraySection.Normalized = false; ArraySections.Add(arraySection); } // Determine array item size ItemSize = (uint)structStride; }
public static int GetValueFromString(Type enumType, string descriptionValue) { int? result = null; var index = 0; foreach (var enumField in enumType.GetFields()) { if (enumField.IsSpecialName) continue; var attribute = (DescriptionAttribute)Attribute.GetCustomAttribute(enumField, typeof(DescriptionAttribute)); if (attribute != null && attribute.Description == descriptionValue) { result = index; break; } index++; } if (result == null) result = (int)Enum.Parse(enumType, descriptionValue); return result.Value; }
public static PropertyMapCollection BuildPropertyMaps(Type objType) { PropertyInfo[] propertyInfos = objType.GetProperties(); //added by Pluto Mei. 2014-1-6 //to support field in map if (propertyInfos.Length > 0) { foreach (PropertyInfo propertyInfo in propertyInfos) { string propertyName = propertyInfo.Name; Type propertyType = propertyInfo.PropertyType; PropertyMap map = new PropertyMap(propertyName, propertyInfo); PropertyMapCache.AddMap(objType, map); if (!propertyType.HasElementType && IsComplexType(propertyType)) { List<string> parentNames = new List<string> { propertyName }; BuildSubPropertyMaps(objType, parentNames, propertyType); } } } else { foreach (FieldInfo fieldInfo in objType.GetFields()) { //add by Pluto Mei.2014-1-6 //TODO: need reflect to support field //old design is strong bind with propertyType //to support field will cost many workload,so delay it. } } return PropertyMapCache.GetMaps(objType); }
/// <summary> /// 获取枚举值的描述信息 /// </summary> /// <param name="enumType">Type,该参数的格式为typeof(需要读的枚举类型)</param> /// <param name="source">枚举值</param> /// <returns></returns> public static string GetDescription(this Enum source, Type enumType) { Type typeDescription = typeof(DescriptionAttribute); System.Reflection.FieldInfo[] fields = enumType.GetFields(); string strText = string.Empty; string strValue = string.Empty; foreach (FieldInfo field in fields) { if (field.FieldType.IsEnum && field.Name.Equals(source.ToString())) { object[] arr = field.GetCustomAttributes(typeDescription, true); if (arr.Length > 0) { DescriptionAttribute aa = (DescriptionAttribute)arr[0]; strText = aa.Description; } else { strText = field.Name; } break; } } return strText; }
public static void ClearSessionProperties(Type type) { for (; type != typeof(object); type = type.BaseType) { FieldInfo[] fields = type.GetFields(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static | BindingFlags.DeclaredOnly); foreach (FieldInfo field in fields) { Type fieldType = field.FieldType; if (fieldType.IsGenericType && fieldType.GetGenericTypeDefinition() == typeof(SessionProperty<>)) { string key = null; if (field.IsDefined(typeof(SessionProperty.KeyAttribute), false)) { SessionProperty.KeyAttribute attr = ((SessionProperty.KeyAttribute[])field.GetCustomAttributes(typeof(SessionProperty.KeyAttribute), false))[0]; key = attr.Key; } if (key == null) { key = BuildSessionKey(field); } HttpContextBase.Current.Session.Remove(key); } } } }
private List<Node> HandleObject(Type type, object o, int level) { var list = new List<Node>(); var fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance); foreach (var field in fields) { list.Add(Process("field", field.Name, o, level)); } var properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance); foreach (var property in properties) { var method = property.GetGetMethod(false); if (method == null) { continue; } try { list.Add(Process("property", property.Name, method.Invoke(o, null), level)); } catch(TargetInvocationException) { } } return list.OrderByDescending(x => x.Name).ToList(); }
/// <summary> /// Returns the name or values as a string, of all fields in the given Type /// </summary> /// <param name="type">Data type</param> /// <param name="separator">Separator for each value</param> /// <param name="parent">Parent name if there are soome sub types of the main Type</param> /// <param name="obj">If the values are printed in the string, we need the object</param> /// <returns>Full string with all name/value fields</returns> public static string GetFieldsAsHeaders(Type type, string separator, string parent = "", object obj = null) { FieldInfo[] fieldInfo; string output = ""; fieldInfo = type.GetFields(BindingFlags.Public | BindingFlags.Instance); foreach (FieldInfo field in fieldInfo) { string value = (obj!= null) ? field.GetValue(obj).ToString() : field.Name; // Loop through sub types as well if (field.FieldType.GetFields(BindingFlags.Public | BindingFlags.Instance).Length > 0) { if (obj != null) { output += GetFieldsAsHeaders(field.FieldType, separator, "", obj.GetType().GetField(field.Name).GetValue(obj)); } else { output += GetFieldsAsHeaders(field.FieldType, separator, value + ".", null); } } else { output += parent + value + separator; } } return output; }
private static ParameterDefinitions GetParameterDefinitions(Type type) { var reflectionFlags = BindingFlags.Static | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic; var allFields = type.GetFields(reflectionFlags).Select(f => new { f.Name, Attribute = f.ResolveAttribute<ParamsAttribute>(), Private = f.IsPrivate, IsStatic = f.IsStatic }); var allProperties = type.GetProperties(reflectionFlags).Select(p => new { p.Name, Attribute = p.ResolveAttribute<ParamsAttribute>(), Private = p.GetSetMethod() == null, IsStatic = p.GetSetMethod() != null && p.GetSetMethod().IsStatic }); var allParameterMembers = allFields.Concat(allProperties).Where(member => member.Attribute != null).ToArray(); var firstPrivateMember = allParameterMembers.FirstOrDefault(member => member.Private); if (firstPrivateMember != null) throw new InvalidOperationException($"Member \"{firstPrivateMember.Name}\" must be public if it has the [Params(..)] attribute applied to it"); var definitions = allParameterMembers.Select(member => new ParameterDefinition(member.Name, member.IsStatic, member.Attribute.Values)).ToArray(); return new ParameterDefinitions(definitions); }
/// <summary> /// 是否需要清除数组 /// </summary> /// <param name="type">类型</param> /// <returns>需要清除数组</returns> private static bool isClearArray(Type type) { foreach (var field in type.GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance)) { var fieldType = field.FieldType; if (fieldType != type && !fieldType.IsPointer) { if (fieldType.IsClass || fieldType.IsInterface) return true; if (!fieldType.IsEnum) { if (fieldType.IsValueType) { bool isClear; if (!isClearArrayCache.TryGetValue(fieldType, out isClear)) { isClearArrayCache.Add(fieldType, isClear = isClearArray(fieldType)); } if (isClear) return true; } else { TmphLog.Default.Add(fieldType.FullName, false, false); return true; } } } } return false; }
/// <summary> /// 根据枚举类型得到其所有的 值 与 枚举定义Description属性 的集合 /// </summary> /// <param name="enumType"></param> /// <returns></returns> public static NameValueCollection GetNVCFromEnumValue(Type enumType) { var nvc = new NameValueCollection(); Type typeDescription = typeof(DescriptionAttribute); FieldInfo[] fields = enumType.GetFields(); foreach (FieldInfo field in fields) { if (field.FieldType.IsEnum) { string strValue = ((int)enumType.InvokeMember(field.Name, BindingFlags.GetField, null, null, null)).ToString(CultureInfo.InvariantCulture); object[] arr = field.GetCustomAttributes(typeDescription, true); string strText; if (arr.Length > 0) { var aa = (DescriptionAttribute)arr[0]; strText = aa.Description; } else { strText = ""; } nvc.Add(strValue, strText); } } return nvc; }
/// <summary> /// Initializes a new instance of the <see cref="EnumWrapper"/> class. /// </summary> /// <param name="t">The enum type.</param> public EnumWrapper(Type t) { if (!t.IsEnum) throw new ArithmeticException(); m_enumType = t; foreach (var m in t.GetFields()) { if (m.FieldType == t) { string originalName = m.Name; string alias = originalName; foreach (var attr in m.GetCustomAttributes(false)) { if (attr is YAXEnumAttribute) { alias = (attr as YAXEnumAttribute).Alias; } } if (alias != originalName) { if (!m_enumMembers.ContainsKey(alias)) m_enumMembers.Add(m.Name, alias); else if (!m_enumMembers.ContainsKey(originalName)) m_enumMembers.Add(m.Name, originalName); else throw new YAXException("Enum alias already exists"); } } } }
private void SetType(Type type) { try { var items = new List<object>(); var values = Enum.GetValues(type); // First we need to get list of all enum fields var fields = type.GetFields(); foreach (var field in fields) { // Continue only for normal fields if (field.IsSpecialName) continue; // Get the first BrowsableAttribute and add the item accordingly. var attr = field.GetCustomAttributes(false).OfType<BrowsableAttribute>().FirstOrDefault(); if (attr == null || attr.Browsable) items.Add(field.GetValue(0)); } this.ItemsSource = items; } catch { } }
/// <summary> /// Gets the value of an Enum, based on it's Description Attribute or named value /// </summary> /// <param name="value">The Enum type</param> /// <param name="description">The description or name of the element</param> /// <returns>The value, or the passed in description, if it was not found</returns> public static object GetEnumValue(Type value, string description) { if (value == null) throw new ArgumentNullException("value"); if (description == null) throw new ArgumentNullException("description", "value was " + (value == null ? "null" : value.ToString())); FieldInfo[] fis = value.GetFields(); foreach (FieldInfo fi in fis) { DescriptionAttribute[] attributes = (DescriptionAttribute[]) fi.GetCustomAttributes( typeof (DescriptionAttribute), false); if (attributes.Length > 0) { if (attributes[0].Description == description) { return fi.GetValue(fi.Name); } } if (fi.Name == description) { return fi.GetValue(fi.Name); } } throw new ArgumentException("Unknown value for enum type " + value.FullName + ": " + description); //return description; }
public static DependencyProperty GetDependencyProperty(string name, Type parent, bool caseSensitive = false) { const string prop = "Property"; var propertyName = name; if (!propertyName.ToLower().EndsWith(prop.ToLower())) { propertyName += prop; } var fieldInfoArray = parent.GetFields(); foreach (var fieldInfo in fieldInfoArray) { if (caseSensitive) { if (fieldInfo.Name != propertyName) continue; var dependencyPropertyField = (DependencyProperty)fieldInfo.GetValue(null); return dependencyPropertyField; } else { if (!string.Equals(fieldInfo.Name, propertyName, StringComparison.CurrentCultureIgnoreCase)) continue; var dependencyPropertyField = (DependencyProperty)fieldInfo.GetValue(null); return dependencyPropertyField; } } throw new Exception("FSR.Reflection.CannotFindDependencyProperty(null, name, caseSensitive)"); }
public static bool HasIntrinsicFields(TypeInfo t) { foreach (var member in t.GetFields(BindingFlags.Static | BindingFlags.Public)) { if (member.Name == "Read" || member.Name == "Write") { return(true); } } return(false); }
public object GetEnumDescription(System.Type value, string nomeCampo) { FieldInfo[] fis = value.GetFields(); foreach (FieldInfo fi in fis) { if (fi.Name == nomeCampo) { return(Atributo <DescriptionAttribute>(fi).Description); } } return(null); }
protected bool MatchComponentPattern(System.Type subject) { const BindingFlags flattenHierarchyMembers = BindingFlags.FlattenHierarchy | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance; var modelInspector = (IModelInspector)this; return(!subject.IsEnum && (subject.Namespace == null || !subject.Namespace.StartsWith("System")) && /* hack */ !modelInspector.IsEntity(subject) && !subject.GetProperties(flattenHierarchyMembers).Cast <MemberInfo>().Concat( subject.GetFields(flattenHierarchyMembers)).Any(m => modelInspector.IsPersistentId(m))); }
public static FieldInfo[] GetAllFieldOfType(System.Type type, System.Reflection.BindingFlags bindings, bool showInConsol = false) { FieldInfo[] allField = type.GetFields(bindings); if (showInConsol) { for (int i = 0; i < allField.Length; i++) { Debug.Log(allField[i].Name); } } return(allField); }
/// <summary> /// Copy original component to destination GameObject. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="original"></param> /// <param name="destination"></param> /// <returns></returns> public static T CopyComponent <T>(this T original, GameObject destination) where T : Component { System.Type type = original.GetType(); Component copy = destination.AddComponent(type); System.Reflection.FieldInfo[] fields = type.GetFields(); foreach (System.Reflection.FieldInfo field in fields) { field.SetValue(copy, field.GetValue(original)); } return(copy as T); }
//------------------------------------------------------------------------------------------------- //행렬데이터 Dictionary로 변환 public Dictionary <TKey, TData> TableToDictionary <TKey, TData>() where TData : class, new() { Dictionary <TKey, TData> result; //{{ 키 이름 찾아오기 ~ string keyName = TSVReader.KeySelector.TryGetKey <TData>(); // }} result = new Dictionary <TKey, TData>(); System.Type type = typeof(TData); System.Reflection.FieldInfo[] arrayFieldInfo = type.GetFields(); for (int i = 0; i < mRowCount; ++i) { TData newData = new TData(); object key = null; if (typeof(string) == typeof(TKey)) { key = ""; } else { key = Activator.CreateInstance(typeof(TKey)); } for (int j = 0; j < arrayFieldInfo.Length; ++j) { System.Type fieldType = arrayFieldInfo[j].FieldType; arrayFieldInfo[j].SetValue(newData, TSVReader.TypeConverter.ConvertType(mArrayData[i, j], fieldType)); //DataAttribute를 사용해서 명시적으로 KeyName을 설정하였다면 if (string.IsNullOrEmpty(keyName) == false) { if (keyName == arrayFieldInfo[j].Name) { key = Convert.ChangeType(mArrayData[i, j], fieldType); } } //KeyName을 설정을 안했다면 첫번째 Field를 KeyName으로 else { if (j == 0) { keyName = arrayFieldInfo[j].Name; } } } result.Add((TKey)key, newData); } return(result); }
PolygonCollider2D CopyComponent(Component original, GameObject destination) { System.Type type = original.GetType(); Component copy = destination.AddComponent(type); // Copied fields can be restricted with BindingFlags System.Reflection.FieldInfo[] fields = type.GetFields(); foreach (System.Reflection.FieldInfo field in fields) { field.SetValue(copy, field.GetValue(original)); } return(copy as PolygonCollider2D); }
public InversListType(NetSystem.Type EntityType) { foreach (FieldInfo field in EntityType.GetFields(BindingFlags.Public | BindingFlags.Instance | BindingFlags.FlattenHierarchy)) { foreach (NetSystem.Attribute attr in field.GetCustomAttributes(true)) { if (attr is ifcInverseAttribute) { this.Add(field); } } } }
private void InitComponent() { System.Type classType = this.GetType(); FieldInfo[] fields = classType.GetFields(); foreach (FieldInfo item in fields) { if (dict.TryGetValue(this.GetType().FullName + item.Name, out cop)) { item.SetValue(this, cop); } } this.InitItem(); }
public static Component CopyComponent(this GameObject destination, Component original) { System.Type type = original.GetType(); Component copy = destination.AddComponent(type); // Copied fields can be restricted with BindingFlags System.Reflection.FieldInfo[] fields = type.GetFields(); foreach (System.Reflection.FieldInfo field in fields) { field.SetValue(copy, field.GetValue(original)); } return(copy); }
// TODO: Consider adding functionality to TypeExtensions to avoid this difference. private static Dictionary <object, string> GetNameMapping(System.Type enumType) { return(enumType.GetFields(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static).ToDictionary(f => f.GetValue(null), f => { var p = f.GetCustomAttributes(typeof(OriginalNameAttribute), false).FirstOrDefault() as OriginalNameAttribute; if (p != null && p.Name != null) { return p.Name; } return f.Name; })); }
private void CreateFieldConfigs() { Fields = Type.GetFields(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public); foreach (var field in Fields) { var cfg = DBUtil.CreateFieldConfig <T>(field); if (cfg.primary) { TableConfig.primaryFieldConfig = cfg; } TableConfig.fields.Add(cfg.name, cfg); } }
public static IEnumerable <FieldInfo> GetAllFields(System.Type t) { if (t == null) { return(Enumerable.Empty <FieldInfo>()); } BindingFlags flags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance | BindingFlags.DeclaredOnly; return(t.GetFields(flags).Concat(GetAllFields(t.BaseType))); }
/// <summary> Method that retrieves all public static fields /// in the class we are methodizing. /// </summary> private void Inspect(System.Type clas) { System.Reflection.FieldInfo[] fields = clas.GetFields(); for (int i = 0; i < fields.Length; i++) { System.Reflection.FieldInfo fieldInfo = fields[i]; if (fieldInfo.IsStatic && fieldInfo.IsPublic) { fieldHash[fields[i].Name] = fields[i]; } } }
/// <summary> /// Given a property or a field try to get the member from a given possible inherited type. /// </summary> /// <param name="member">The member to find.</param> /// <param name="reflectedType">The type where find the member.</param> /// <returns>The member from the reflected-type or the original <paramref name="member"/> where the <paramref name="member"/> is not accessible from <paramref name="reflectedType"/>.</returns> public static MemberInfo GetMemberFromReflectedType(this MemberInfo member, System.Type reflectedType) { if (member == null) { throw new ArgumentNullException("member"); } if (reflectedType == null) { throw new ArgumentNullException("reflectedType"); } var field = member as FieldInfo; if (field != null && field.IsPrivate) { return(member); } var property = member as PropertyInfo; if (property != null) { var propertyGetter = property.GetGetMethod(true); if (propertyGetter.IsPrivate) { return(member); } if (property.DeclaringType.IsInterface) { System.Type[] interfaces = reflectedType.GetInterfaces(); var @interface = property.DeclaringType; if (!interfaces.Contains(@interface)) { return(member); } var reflectedCandidateProps = reflectedType.GetProperties(PropertiesOfClassHierarchy); InterfaceMapping memberMap = reflectedType.GetInterfaceMap(@interface); for (int i = 0; i < memberMap.TargetMethods.Length; i++) { if (memberMap.InterfaceMethods[i] == propertyGetter) { return(reflectedCandidateProps.Single(pi => pi.GetGetMethod(true) == memberMap.TargetMethods[i])); } } return(member); } } var reflectedTypeProperties = reflectedType.GetProperties(PropertiesOfClassHierarchy); var members = reflectedTypeProperties.Cast <MemberInfo>().Concat(reflectedType.GetFields(PropertiesOfClassHierarchy)); var result = members.FirstOrDefault(m => m.Name.Equals(member.Name) && m.GetPropertyOrFieldType().Equals(member.GetPropertyOrFieldType())); return(result ?? member); }
public override TypeConverter.StandardValuesCollection GetStandardValues(ITypeDescriptorContext context) { List <int> values = new List <int>(); FieldInfo[] fis = myVal.GetFields(); foreach (FieldInfo fi in fis) { if ((fi.Attributes & FieldAttributes.Literal) != 0) { values.Add((int)fi.GetRawConstantValue()); } } return(new StandardValuesCollection(values)); }
public static System.Reflection.FieldInfo GetFieldInfoNoCase(object obj, string sField) { sField = sField.ToLower(); System.Type type = obj.GetType(); System.Reflection.FieldInfo[] fieldInfos = type.GetFields(); foreach (System.Reflection.FieldInfo fieldInfo in fieldInfos) { if (fieldInfo.Name.ToLower() == sField) { return(fieldInfo); } } return(null); }
public static void DeepReset <T>(T obj) { System.Type type = typeof(T); T local = Activator.CreateInstance <T>(); if (local == null) { throw new SystemException(string.Format("Unable to instantiate type {0} with default constructor.", type.Name)); } foreach (FieldInfo info in type.GetFields(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance)) { info.SetValue(obj, info.GetValue(local)); } }
// Get only public methods, or public/protected if type is not sealed public static FieldInfo[] GetFields(System.Type monoType) { FieldInfo[] fieldInfos = monoType.GetFields(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static); List <FieldInfo> finalInfos = new List <FieldInfo>(); foreach (FieldInfo fieldInfo in fieldInfos) { if (fieldInfo.IsPublic || (monoType.IsValueType && !fieldInfo.IsStatic)) { finalInfos.Add(fieldInfo); } } return(finalInfos.ToArray()); }
private static MemberInfo[] GetTypeMembers(System.Type type) { List <MemberInfo> list = new List <MemberInfo>(); PropertyInfo[] pis = type.GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.FlattenHierarchy); Array.ForEach(pis, delegate(PropertyInfo pi) { list.Add(pi); }); FieldInfo[] fis = type.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.FlattenHierarchy); Array.ForEach(fis, delegate(FieldInfo fi) { list.Add(fi); }); return(list.ToArray()); }
/// <summary> /// 获取指定类型的全部定义字段 /// </summary> /// <param name="type">要获取的类的类型</param> /// <returns>字段集合</returns> public static object[] GetTypeItems(System.Type type) { ArrayList items = new ArrayList(); FieldInfo[] fis = type.GetFields(); foreach (FieldInfo fi in fis) { if (fi.FieldType.Equals(typeof(StringItem))) { items.Add(fi.GetValue(null)); } } return(items.ToArray()); }
public static string DisplayObjectInfo(Object o) { StringBuilder sb = new StringBuilder(); // Include the type of the object System.Type type = o.GetType(); sb.Append("Type: " + type.Name); // Include information for each Field sb.Append("\r\n\r\nFields:"); System.Reflection.FieldInfo[] fi = type.GetFields(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance); if (fi.Length > 0) { foreach (FieldInfo f in fi) { if (f.FieldType.IsValueType) { sb.Append("\r\n " + f.ToString() + " = " + f.GetValue(o)); } else { var test = f.GetValue(o); sb.Append("\r\n " + f.ToString() + " = " + DisplayObjectInfo(f.GetValue(o))); } } } else { sb.Append("\r\n None"); } // Include information for each Property sb.Append("\r\n\r\nProperties:"); System.Reflection.PropertyInfo[] pi = type.GetProperties(); if (pi.Length > 0) { foreach (PropertyInfo p in pi) { sb.Append("\r\n " + p.ToString() + " = " + p.GetValue(o, null)); } } else { sb.Append("\r\n None"); } return(sb.ToString()); }
static StackObject *GetFields_7(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, 1); ptr_of_this_method = ILIntepreter.Minus(__esp, 1); System.Type instance_of_this_method = (System.Type) typeof(System.Type).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack)); __intp.Free(ptr_of_this_method); var result_of_this_method = instance_of_this_method.GetFields(); return(ILIntepreter.PushObject(__ret, __mStack, result_of_this_method)); }
public Dictionary <string, ColumnInfo> GetTableColumnsInfo(System.Type table) { string tableName = table.Name; Dictionary <string, ColumnInfo> columns = new Dictionary <string, ColumnInfo> (); FieldInfo[] fields = table.GetFields(); for (int i = 0; i < fields.Length; ++i) { string attributes = DBFieldAttribute.GetDBAttributes(fields[i]); ColumnInfo c = new ColumnInfo(fields[i].Name, GetCTypeToSqlType(fields[i].FieldType), attributes); columns.Add(c._name, c); } return(columns); }
static public string GetQuery(MonoSQLiteManager dbManager, System.Type table) { Dictionary <string, ColumnInfo> columns = new Dictionary <string, ColumnInfo>(); FieldInfo[] fields = table.GetFields(); for (int i = 0; i < fields.Length; ++i) { string attributes = DBFieldAttribute.GetDBAttributes(fields[i]); ColumnInfo c = new ColumnInfo(fields[i].Name, dbManager.GetCTypeToSqlType(fields[i].FieldType), attributes); columns.Add(c._name, c); } return(GetQuery(dbManager, table.Name, columns)); }
private void DeserializeTo(System.Type type, object obj) { System.Reflection.BindingFlags bindingAttr = System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public; System.Reflection.PropertyInfo[] properties = type.GetProperties(bindingAttr); System.Reflection.PropertyInfo[] array = properties; for (int i = 0; i < array.Length; i++) { System.Reflection.PropertyInfo propertyInfo = array[i]; if (propertyInfo.CanWrite) { string attrName = Serializer.GetAttrName(propertyInfo.Name); System.Type propertyType = propertyInfo.PropertyType; if (ReflectionUtils.IsPrimitiveType(propertyType)) { object value; if (this.GetAttrValue(propertyInfo, propertyType, attrName, out value)) { propertyInfo.SetValue(obj, value, null); } } else { object value = this.DeserializeObject(attrName, propertyType); propertyInfo.SetValue(obj, value, null); } } } System.Reflection.FieldInfo[] fields = type.GetFields(bindingAttr); System.Reflection.FieldInfo[] array2 = fields; for (int i = 0; i < array2.Length; i++) { System.Reflection.FieldInfo fieldInfo = array2[i]; string attrName = Serializer.GetAttrName(fieldInfo.Name); System.Type fieldType = fieldInfo.FieldType; if (ReflectionUtils.IsPrimitiveType(fieldType)) { object value; if (this.GetAttrValue(fieldInfo, fieldType, attrName, out value)) { fieldInfo.SetValue(obj, value); } } else { object value = this.DeserializeObject(attrName, fieldType); fieldInfo.SetValue(obj, value); } } }
/// <summary> /// 获取项集合,文本设置为Description,值为Value /// </summary> /// <param name="type">枚举类型</param> public static List <Item> GetItems(MicrosoftSystem.Type type) { type = Common.GetType(type); if (type.IsEnum == false) { throw new MicrosoftSystem.InvalidOperationException($"类型 {type} 不是枚举"); } var result = new List <Item>(); foreach (var field in type.GetFields()) { AddItem(type, result, field); } return(result.OrderBy(t => t.SortId).ToList()); }
private static void GenEnum(System.Type type) { sb.Append(type.Name + " = {} \r\n\r\n"); FieldInfo[] fields = type.GetFields(BindingFlags.GetField | BindingFlags.Public | BindingFlags.Static); for (int i = 0; i < fields.Length; i++) { FieldInfo field = fields[i]; object[] comment = field.GetCustomAttributes(true); sb.Append(field.Name + " = nil;\r\n\r\n"); } }
public override DecodedObject <object> decodeEnumItem(DecodedObject <object> decodedTag, System.Type objectClass, System.Type enumClass, ElementInfo elementInfo, System.IO.Stream stream) { //int min = 0, max = enumClass.GetFields().Length; int min = 0, max = 0; foreach (FieldInfo enumItem in enumClass.GetFields()) { if (CoderUtils.isAttributePresent <ASN1EnumItem>(enumItem)) { max++; } } if (max <= 0) { throw new Exception("Unable to present any enum item!"); } int enumItemIdx = (int)decodeConstraintNumber(min, max - 1, (BitArrayInputStream)stream); DecodedObject <object> result = new DecodedObject <object>(); int idx = 0; foreach (FieldInfo enumItem in enumClass.GetFields()) { if (CoderUtils.isAttributePresent <ASN1EnumItem>(enumItem)) { if (idx++ == enumItemIdx) { ASN1EnumItem enumItemObj = CoderUtils.getAttribute <ASN1EnumItem>(enumItem); result.Value = enumItemObj.Tag; break; } } } return(result); }
static void Main(string[] args) { var test = new Test(); System.Type type = test.GetType(); FieldInfo[] fields = type.GetFields(); SomethingAttribute MyAttribute = (SomethingAttribute)Attribute.GetCustomAttribute(type, typeof(SomethingAttribute)); Console.WriteLine(MyAttribute.Developer); DateTime dateTime = (DateTime)Activator.CreateInstance(typeof(DateTime)); }