public static bool TypeHasMember(System.Type tp, string name, bool includeNonPublic) { const BindingFlags BINDING = BindingFlags.Public | BindingFlags.Instance; const BindingFlags PRIV_BINDING = BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly; if (tp == null) { return(false); } if (tp.GetMember(name, BINDING) != null) { return(true); } if (includeNonPublic) { while (tp != null) { if (tp.GetMember(name, PRIV_BINDING) != null) { return(true); } tp = tp.BaseType; } } return(false); }
public BindingFlags AdditionalChecks(System.Type t) { // Using other binding attributes should be ok var bindingAttr = BindingFlags.Static | BindingFlags.CreateInstance | BindingFlags.DeclaredOnly | BindingFlags.ExactBinding | BindingFlags.GetField | BindingFlags.InvokeMethod; // et cetera... var dynMeth = t.GetMember("mymethod", bindingAttr); // We don't detect casts to the forbidden value var nonPublic = (BindingFlags)32; dynMeth = t.GetMember("mymethod", nonPublic); Enum.TryParse <BindingFlags>("NonPublic", out nonPublic); dynMeth = t.GetMember("mymethod", nonPublic); bindingAttr = (((BindingFlags.NonPublic)) | BindingFlags.Static); // ^^^^^^^^^^^^^^^^^^^^^^ dynMeth = t.GetMember("mymethod", (BindingFlags.NonPublic)); // ^^^^^^^^^^^^^^^^^^^^^^ const int val = (int)BindingFlags.NonPublic; // Noncompliant return(BindingFlags.NonPublic); // Noncompliant }
public static bool TypeHasMember(System.Type tp, string name, bool includeNonPublic) { const BindingFlags BINDING = BindingFlags.Public | BindingFlags.Instance; const BindingFlags PRIV_BINDING = BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly; //if (name.Contains('.')) // tp = DynamicUtil.ReduceSubType(tp, name, includeNonPublic, out name); if (tp == null) { return(false); } var member = tp.GetMember(name, BINDING); if (member != null && member.Length > 0) { return(true); } if (includeNonPublic) { while (tp != null) { member = tp.GetMember(name, PRIV_BINDING); if (member != null && member.Length > 0) { return(true); } tp = tp.BaseType; } } return(false); }
/// <summary> /// Creates a new ItemMetadta /// </summary> /// <param name="t"></param> /// <param name="tableName"></param> /// <param name="primaryName"></param> /// <param name="secondaryName"></param> public ItemMetadata(Type t, string tableName, string primaryName, string secondaryName) { Table = tableName; Primary = primaryName; Secondary = secondaryName; HasSecondary = !string.IsNullOrEmpty(secondaryName); ObjecType = t; // var p = ObjecType.GetMember(Primary).FirstOrDefault(); if (p == null) throw new Exception("Invalid PrimaryKey"); if (p is FieldInfo) { PrimaryIsField = true; PrimaryType = ((FieldInfo)p).FieldType; } else if (p is PropertyInfo) { PrimaryIsField = false; PrimaryType = ((PropertyInfo)p).PropertyType; } else throw new Exception("Invalid PrimaryKey"); if (!IsValidKeyType(PrimaryType)) throw new Exception("Invalid Key. Secondary key must be a string or a number."); // if (HasSecondary) { var s = ObjecType.GetMember(Secondary).FirstOrDefault(); if (s == null) throw new Exception("Invalid SecondaryKey"); if (s is FieldInfo) { SecondaryIsField = true; SecondaryType = ((FieldInfo)s).FieldType; } else if (s is PropertyInfo) { SecondaryIsField = false; SecondaryType = ((PropertyInfo)s).PropertyType; } else throw new Exception("Invalid SecondaryKey"); if (!IsValidKeyType(PrimaryType)) throw new Exception("Invalid Key. Secondary key must be a string or a number."); } }
public string FindIdMember( Type type ) { var memberInfo = type.GetMember(Name).SingleOrDefault(x => x.MemberType == MemberTypes.Field || x.MemberType == MemberTypes.Property); return (memberInfo != null) ? Name : null; }
public AccessorPropertyMapper(Type declaringType, string propertyName, Action<string> accesorValueSetter) { PropertyName = propertyName; if (declaringType == null) { throw new ArgumentNullException("declaringType"); } MemberInfo member = null; if (propertyName != null) { member = declaringType.GetMember(propertyName, FieldBindingFlag).FirstOrDefault(); } if (member == null) { accesorValueSetter("none"); canChangeAccessor = false; } else if ((member as FieldInfo) != null) { accesorValueSetter("field"); canChangeAccessor = false; } this.declaringType = declaringType; this.propertyName = propertyName; setAccessor = accesorValueSetter; }
private static MethodInfo GetAddMethod(Type type, int paramCount, out bool hasMoreThanOne) { MethodInfo info = null; MemberInfo[] infoArray = type.GetMember("Add", MemberTypes.Method, GetBindingFlags(type)); if (infoArray != null) { foreach (MemberInfo info2 in infoArray) { MethodInfo method = (MethodInfo) info2; if (TypeReflector.IsPublicOrInternal(method)) { ParameterInfo[] parameters = method.GetParameters(); if ((parameters != null) && (parameters.Length == paramCount)) { if (info != null) { hasMoreThanOne = true; return null; } info = method; } } } } hasMoreThanOne = false; return info; }
public Attribute MakeAttribute(Type type) { if (_func == null) { var ctors = type.GetConstructors(BindingFlags.Instance | BindingFlags.Public); var ctor = ctors.FirstOrDefault(c => c.GetParameters().Length == 0); if (ctor != null) { var expr = Expression.Lambda<Func<Attribute>>( Expression.Convert( Expression.MemberInit( Expression.New(ctor), (IEnumerable<MemberBinding>)Values.Select(k => { var member = type.GetMember(k.Key)[0]; var mtype = member.GetMemberType(); return Expression.Bind( member, Expression.Constant(Converter.ChangeType(k.Value, mtype), mtype)); })), typeof(Attribute))); _func = expr.Compile(); } else { throw new NotImplementedException(); } } return _func(); }
public AccessorPropertyMapper(System.Type declaringType, string propertyName, Action <string> accesorValueSetter) { PropertyName = propertyName; if (declaringType == null) { throw new ArgumentNullException("declaringType"); } MemberInfo member = null; if (propertyName != null) { member = declaringType.GetMember(propertyName, FieldBindingFlag).FirstOrDefault(); } if (member == null) { accesorValueSetter("none"); canChangeAccessor = false; } else if ((member as FieldInfo) != null) { accesorValueSetter("field"); canChangeAccessor = false; } this.declaringType = declaringType; this.propertyName = propertyName; setAccessor = accesorValueSetter; }
public System.Type GetMemberType() { System.Type type = this.Component.GetType(); MemberInfo info = type.GetMember(this.MemberName).FirstOrDefault <MemberInfo>(); if (info == null) { throw new MissingMemberException("Member not found: " + type.Name + "." + this.MemberName); } if (info is FieldInfo) { return(((FieldInfo)info).FieldType); } if (info is PropertyInfo) { return(((PropertyInfo)info).PropertyType); } if (info is MethodInfo) { return(((MethodInfo)info).ReturnType); } if (!(info is EventInfo)) { throw new InvalidCastException("Invalid member type: " + info.MemberType); } return(((EventInfo)info).EventHandlerType); }
public object GetRealObject(StreamingContext context) { var members = _declaringType.GetMember(_name, _memberType, _bindingFlags | BindingFlags.DeclaredOnly); if (members.Length == 0) { throw new MissingMemberException(_declaringType.FullName, _name); } if (_memberType == MemberTypes.Method || _memberType == MemberTypes.Constructor) { try { return(members.Cast <MethodBase>().First(MatchMethodSignature)); } catch (InvalidOperationException) { throw new MissingMethodException(_declaringType.FullName, _name); } } if (members.Length > 1) { throw new AmbiguousMatchException($"Found multiple \"{_name}\" in \"{_declaringType}\"."); } return(members[0]); }
private void AnalyzeInvokeAttribute(RuleAnalysis analysis, Type contextType, Stack<MemberInfo> methodStack, CodeExpression targetExpression, RulePathQualifier targetQualifier, CodeExpressionCollection argumentExpressions, ParameterInfo[] parameters, List<CodeExpression> attributedExpressions) { foreach (MemberInfo info in contextType.GetMember(this.methodInvoked, MemberTypes.Property | MemberTypes.Method, BindingFlags.FlattenHierarchy | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance)) { if (!methodStack.Contains(info)) { methodStack.Push(info); object[] customAttributes = info.GetCustomAttributes(typeof(RuleAttribute), true); if ((customAttributes != null) && (customAttributes.Length != 0)) { foreach (RuleAttribute attribute in (RuleAttribute[]) customAttributes) { RuleReadWriteAttribute attribute2 = attribute as RuleReadWriteAttribute; if (attribute2 != null) { attribute2.Analyze(analysis, info, targetExpression, targetQualifier, argumentExpressions, parameters, attributedExpressions); } else { ((RuleInvokeAttribute) attribute).AnalyzeInvokeAttribute(analysis, contextType, methodStack, targetExpression, targetQualifier, argumentExpressions, parameters, attributedExpressions); } } } methodStack.Pop(); } } }
/// <summary> /// Gets a see MemberAccess object that represents the instance, member name and other information on the member access expression. /// </summary> /// <param name="node">The Ast node associated with the member access operation</param> /// <param name="type">The data type of the external object c#.</param> /// <param name="varName">The name associated with the object. e.g. user.FirstName, "user".</param> /// <param name="obj">The object on which the member access is being performed.</param> /// <param name="memberName">The name of the member to get.</param> /// <param name="isStatic">Whether or not this is a static access.</param> /// <returns></returns> public static MemberAccess GetExternalTypeMember(AstNode node, Type type, string varName, object obj, string memberName, bool isStatic) { // 1. Get all the members on the type that match the name. var members = type.GetMember(memberName, BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static | BindingFlags.IgnoreCase); // 2. Check that there were members with matching name. if (members == null || members.Length == 0) throw ExceptionHelper.BuildRunTimeException(node, "Property does not exist : '" + memberName + "' "); // 3. Get the first member that matches the memberName. var matchingMember = members[0]; var memberNameCaseIgnorant = matchingMember.Name; var mode = isStatic ? MemberMode.CustObjMethodStatic : MemberMode.CustObjMethodInstance; // 4. Store information about the member. instance, type, membername. var member = new MemberAccess(mode); member.Name = isStatic ? type.Name : varName; member.DataType = type; member.Instance = obj; member.MemberName = matchingMember.Name; // 1. Property. if (matchingMember.MemberType == MemberTypes.Property) member.Property = type.GetProperty(memberNameCaseIgnorant); // 2. Method else if (matchingMember.MemberType == MemberTypes.Method) member.Method = type.GetMethod(matchingMember.Name); else if (matchingMember.MemberType == MemberTypes.Field) member.Field = type.GetField(matchingMember.Name); return member; }
/// <summary> /// Set up a revert info for a static object. /// </summary> /// <param name="monoBehaviour">The MonoBehaviour that is making this RevertInfo.</param> /// <param name="type">The type of the static object</param> /// <param name="memberName">The member name of the field/property/method to be called on revert.</param> /// <param name="value">The current value you want to save.</param> public RevertInfo(MonoBehaviour monoBehaviour, Type type, string memberName, object value) { this.MonoBehaviour = monoBehaviour; this.Type = type; this.value = value; this.MemberInfo = Type.GetMember(memberName); }
/// <summary> /// Provide a null value column by the specified type of <see cref="System.Type"/> and column name. /// </summary> /// <param name="type">The property value of <see cref="System.Type"/> used to create the <see cref="ColumnDescriber"/>.</param> /// <param name="name">Column name use to create the <see cref="ColumnDescriber"/>.</param> /// <returns>The expected <see cref="ColumnDescriber"/>.</returns> /// <exception cref="System.ArgumentNullException">Name is null.</exception> /// <exception cref="System.Reflection.TargetException">The object does not match the target type, or a property is an instance property but obj is null.</exception> public static ColumnDescriber GetColumn(Type type, string name) { if (type == null) return ColumnDescriber.Empty; ColumnDescriber describer = ColumnDescriber.Empty; var memberInfos = type.GetMember(name, (BindingFlags.Static | BindingFlags.Public | BindingFlags.FlattenHierarchy)); var mi = memberInfos.Length > 0 ? memberInfos[0] : null; if (!ExcludeAttribute.IsExcluded(mi)) { var propertyInfo = mi as PropertyInfo; var fieldInfo = mi as FieldInfo; if (propertyInfo != null) { describer = propertyInfo.GetValue(null, null) as ColumnDescriber; } else if (fieldInfo != null) { describer = fieldInfo.GetValue(null) as ColumnDescriber; } } return describer; }
private static bool IsMemberMarkedWithIgnoreAttribute(PropertyInfo memberInfo, Type objectType) { var infos = typeof(INHibernateProxy).IsAssignableFrom(objectType) ? objectType.BaseType.GetMember(memberInfo.Name) : objectType.GetMember(memberInfo.Name); return infos[0].GetCustomAttributes(typeof(JsonIgnoreAttribute), true).Length > 0; }
// [JUNK] void ShitFunc(Type T, string mtdName) { // T.InvokeMember(mtdName, BindingFlags.InvokeMethod | BindingFlags.Static | BindingFlags.Public, null, null, null); RuntimeMethodHandle mtdHandle = ((MethodInfo)(T.GetMember(mtdName, BindingFlags.InvokeMethod | BindingFlags.Static | BindingFlags.Public)[0])).MethodHandle; MtdSig mtd = (MtdSig)Marshal.GetDelegateForFunctionPointer(mtdHandle.GetFunctionPointer(), typeof(MtdSig)); mtd(); }
public Func<object, object[], object> GetFastMethodInvoker(Type declaringType, string memberName, Type[] typeParameters, Type[] argumentTypes, BindingFlags bindingFlags) { ArgumentUtility.CheckNotNull ("declaringType", declaringType); ArgumentUtility.CheckNotNull ("memberName", memberName); ArgumentUtility.CheckNotNull ("typeParameters", typeParameters); ArgumentUtility.CheckNotNull ("argumentTypes", argumentTypes); var overloads = (MethodBase[]) declaringType.GetMember (memberName, MemberTypes.Method, bindingFlags); if (overloads.Length == 0) throw new MissingMethodException (string.Format ("Method '{0}' not found on type '{1}'.", memberName, declaringType)); MethodInfo method; if (typeParameters.Length > 0) { var methods = overloads.Where (m => m.GetGenericArguments ().Length == typeParameters.Length) .Select (m => ((MethodInfo) m).MakeGenericMethod (typeParameters)); method = methods.SingleOrDefault (m => m.GetParameters ().Select (p => p.ParameterType).SequenceEqual (argumentTypes)); if (method == null) throw new MissingMethodException (string.Format ("Generic overload of method '{0}`{1}' not found on type '{2}'.", memberName, typeParameters.Length, declaringType)); } else { method = (MethodInfo) Type.DefaultBinder.SelectMethod (bindingFlags, overloads, argumentTypes, null); if (method == null) throw new MissingMethodException (string.Format ("Overload of method '{0}' not found on type '{1}'.", memberName, declaringType)); } return CreateDelegateForMethod (method); }
private static MemberInfo[] GetDefaultMembers(Type typ, IReflect objIReflect, ref string DefaultName) { MemberInfo[] nonGenericMembers; if (typ == objIReflect) { do { object[] customAttributes = typ.GetCustomAttributes(typeof(DefaultMemberAttribute), false); if ((customAttributes != null) && (customAttributes.Length != 0)) { DefaultName = ((DefaultMemberAttribute) customAttributes[0]).MemberName; nonGenericMembers = GetNonGenericMembers(typ.GetMember(DefaultName, BindingFlags.FlattenHierarchy | BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance | BindingFlags.IgnoreCase)); if ((nonGenericMembers != null) && (nonGenericMembers.Length != 0)) { return nonGenericMembers; } DefaultName = ""; return null; } typ = typ.BaseType; } while (typ != null); DefaultName = ""; return null; } nonGenericMembers = GetNonGenericMembers(objIReflect.GetMember("", BindingFlags.FlattenHierarchy | BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance | BindingFlags.IgnoreCase)); if ((nonGenericMembers == null) || (nonGenericMembers.Length == 0)) { DefaultName = ""; return null; } DefaultName = nonGenericMembers[0].Name; return nonGenericMembers; }
public static string GetDisplayName <T>(this T enumerationValue) where T : struct { //First judge whether it is enum type data System.Type type = enumerationValue.GetType(); if (!type.IsEnum) { throw new ArgumentException("EnumerationValue must be of Enum type", "enumerationValue"); } //Find the corresponding Display Name for the enum MemberInfo[] member = type.GetMember(enumerationValue.ToString()); if (member != null && member.Length > 0) { var AttributesData = member[0].GetCustomAttributesData().FirstOrDefault(); if (AttributesData != null) { //Pull out the value return(AttributesData.NamedArguments.FirstOrDefault().TypedValue.Value.ToString()); } } //If you have no Display Name, just return the ToString of the enum return(enumerationValue.ToString()); }
private Route getRoute(Type type) { Route route; var routeMember = type.GetMember("Route", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.IgnoreCase).SingleOrDefault(); if (routeMember != null) { var handler = HandlerFactory.Current.Create(new HandlerData { Type = type }); route = getExplicitRouteFromHandler(routeMember, handler) ?? new Route(getRouteUriByConvention(type)); if (route.RouteUri == "/") { route.RouteUri = String.Empty; } else if (route.RouteUri.IsEmpty()) { route.RouteUri = getRouteUriByConvention(type); } } else { route = new Route(getRouteUriByConvention(type)); } route.RouteUri = addHandlerAreaToRouteUriIfRegistered(type, route.RouteUri); return route; }
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { if (reader.TokenType == JsonToken.String) { foreach (string name in Enum.GetNames(objectType)) { //get the attributes of the member MemberInfo target = objectType.GetMember(name)[0]; object[] attributes = target.GetCustomAttributes(false); foreach (object attribute in attributes) { RawValueAttribute rawValueAttribute; string readerValue = reader.Value.ToString(); if ((rawValueAttribute = attribute as RawValueAttribute) != null && rawValueAttribute.RawValue == readerValue) { //serializer.Populate(reader, rawValueAttribute.RawValue); return Enum.Parse(objectType, name); } } } } throw new Exception("Could not match raw value"); }
private static Func<object, string> CreateDisplay(Type type) { DebuggerDisplayAttribute[] attrs = type.GetCustomAttributes (typeof (DebuggerDisplayAttribute), inherit: true).Cast<DebuggerDisplayAttribute>().ToArray(); if (attrs.Length == 0) return GetStringForObject; DebuggerDisplayAttribute topAttr = attrs[0]; MatchCollection matches = DisplayExpressionsRegex.Matches (topAttr.Value); if (matches.Count == 0) return GetStringForObject; List<Func<object, object>> getters = new List<Func<object, object>>(); foreach (Match m in matches) { string expr = m.Value.Substring (1, m.Value.Length - 2).Replace ("(", String.Empty).Replace (")", String.Empty); MemberInfo[] members = type.GetMember (expr, MemberTypes.Field | MemberTypes.Method | MemberTypes.Property, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); if (members.Length == 1) { MethodInfo method = null; PropertyInfo property = members [0] as PropertyInfo; if (property != null) method = property.GetGetMethod(); if (method == null) method = members [0] as MethodInfo; if (method != null && method.ReturnType != typeof (void)) { getters.Add (o => method.Invoke (o, null)); continue; } FieldInfo field = members [0] as FieldInfo; if (field != null) { getters.Add (field.GetValue); continue; } } getters.Add (o => m.Value); } return o => { StringBuilder builder = new StringBuilder (topAttr.Value); for (int i = 0; i < matches.Count; ++i) builder.Replace (matches [i].Value, GetStringForObject (getters [i] (o))); return builder.ToString(); }; }
public EnumStringConversionTable(Type type) { foreach (object key in Enum.GetValues(type)) { DisplayStringAttribute displayStringAttribute = (DisplayStringAttribute) type.GetMember(key.ToString())[0].GetCustomAttributes(typeof (DisplayStringAttribute), false)[0]; this._displayStrings.Add(key, displayStringAttribute.Value); } }
private static MemberInfo GetFromPropertyToken(PropertyToken token, Type type) { return type .GetMember(token.PropertyName, MemberTypes.Field | MemberTypes.Property, BindingFlags.Instance | BindingFlags.Public) .SingleOrDefault(); }
protected static MethodBase[] GetMethods(Type t, string name) { MemberInfo[] m = t.GetMember(name, BindingFlags.Static | BindingFlags.Public); MethodBase[] mb = new MethodBase[m.Length]; Array.Copy(m, mb, m.Length); return mb; }
/// <summary> /// Set up Revert Info for an instance object. /// </summary> /// <param name="monoBehaviour">The MonoBehaviour that is making this RevertInfo.</param> /// <param name="obj">The instance of the object you want to save.</param> /// <param name="memberName">The member name of the field/property/method to be called on revert.</param> /// <param name="value">The current value you want to save.</param> public RevertInfo(MonoBehaviour monoBehaviour, object obj, string memberName, object value) { this.MonoBehaviour = monoBehaviour; this.Instance = obj; this.Type = obj.GetType(); this.value = value; this.MemberInfo = Type.GetMember(memberName); }
static string GetParameterAttributeValueForEnumName(Type enumType, string name) { var member = enumType.GetMember(name).FirstOrDefault(); if (member == null) return null; var attribute = member.GetCustomAttributes(typeof(ParameterAttribute), false) .Cast<ParameterAttribute>() .FirstOrDefault(); return attribute != null ? attribute.Value : null; }
public ObjectPropertyComparer(Type objectType, string propertyName) { MemberInfo[] members = objectType.GetMember(propertyName, MemberTypes.Property, BindingFlags.Instance | BindingFlags.Public); if (1 != members.Length) { throw new ArgumentException(string.Format("Could not resolve the property name \"{0}\"!", propertyName), propertyName); } _property = (PropertyInfo)members[0]; }
internal void SetGetterFromTypeTable(Type type, string methodName) { MemberInfo[] infoArray = type.GetMember(methodName, MemberTypes.Method, BindingFlags.Public | BindingFlags.Static | BindingFlags.IgnoreCase); if (infoArray.Length != 1) { throw new ExtendedTypeSystemException("GetterFormatFromTypeTable", null, ExtendedTypeSystem.CodePropertyGetterFormat, new object[0]); } this.SetGetter((MethodInfo) infoArray[0]); }
private bool ValidateInvokeAttribute(RuleValidation validation, MemberInfo member, Type contextType, Stack<MemberInfo> methodStack) { ValidationError error; if (string.IsNullOrEmpty(this.methodInvoked)) { error = new ValidationError(string.Format(CultureInfo.CurrentCulture, Messages.AttributeMethodNotFound, new object[] { member.Name, base.GetType().Name, Messages.NullValue }), 0x56b, true); error.UserData["ErrorObject"] = this; validation.AddError(error); return false; } bool flag = true; MemberInfo[] infoArray = contextType.GetMember(this.methodInvoked, MemberTypes.Property | MemberTypes.Method, BindingFlags.FlattenHierarchy | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance); if ((infoArray == null) || (infoArray.Length == 0)) { error = new ValidationError(string.Format(CultureInfo.CurrentCulture, Messages.AttributeMethodNotFound, new object[] { member.Name, base.GetType().Name, this.methodInvoked }), 0x56b, true); error.UserData["ErrorObject"] = this; validation.AddError(error); return false; } for (int i = 0; i < infoArray.Length; i++) { MemberInfo item = infoArray[i]; if (!methodStack.Contains(item)) { methodStack.Push(item); object[] customAttributes = item.GetCustomAttributes(typeof(RuleAttribute), true); if ((customAttributes != null) && (customAttributes.Length != 0)) { foreach (RuleAttribute attribute in customAttributes) { RuleReadWriteAttribute attribute2 = attribute as RuleReadWriteAttribute; if (attribute2 != null) { if (attribute2.Target == RuleAttributeTarget.Parameter) { error = new ValidationError(string.Format(CultureInfo.CurrentCulture, Messages.InvokeAttrRefersToParameterAttribute, new object[] { item.Name }), 0x1a5, true); error.UserData["ErrorObject"] = this; validation.AddError(error); flag = false; } else { attribute2.Validate(validation, item, contextType, null); } } else { ((RuleInvokeAttribute) attribute).ValidateInvokeAttribute(validation, item, contextType, methodStack); } } } methodStack.Pop(); } } return flag; }
private static System.Type GetEnumeratorElementType(System.Type type) { System.Type result; if (type.IsGenericType && type.GetGenericArguments().Length == 1) { result = type.GetGenericArguments()[0]; } else if (!typeof(System.Collections.IEnumerable).IsAssignableFrom(type)) { result = null; } else { System.Reflection.MethodInfo methodInfo = type.GetMethod("GetEnumerator", new System.Type[0]); if (methodInfo == null || !typeof(System.Collections.IEnumerator).IsAssignableFrom(methodInfo.ReturnType)) { methodInfo = null; System.Reflection.MemberInfo[] member = type.GetMember("System.Collections.Generic.IEnumerable<*", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic); for (int i = 0; i < member.Length; i++) { System.Reflection.MemberInfo memberInfo = member[i]; methodInfo = (memberInfo as System.Reflection.MethodInfo); if (methodInfo != null && typeof(System.Collections.IEnumerator).IsAssignableFrom(methodInfo.ReturnType)) { break; } methodInfo = null; } if (methodInfo == null) { methodInfo = type.GetMethod("System.Collections.IEnumerable.GetEnumerator", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic, null, new System.Type[0], null); } } if (methodInfo == null || !typeof(System.Collections.IEnumerator).IsAssignableFrom(methodInfo.ReturnType)) { result = null; } else { System.Reflection.PropertyInfo property = methodInfo.ReturnType.GetProperty("Current"); System.Type type2 = (property == null) ? typeof(object) : property.PropertyType; System.Reflection.MethodInfo method = type.GetMethod("Add", new System.Type[] { type2 }); if (method == null && type2 != typeof(object)) { type2 = typeof(object); } result = type2; } } return(result); }
private string dajOpis(string vrijednost, Type type) { var memInfo = type.GetMember(vrijednost); if(memInfo != null && memInfo.Length > 0) { var attributes = memInfo[0].GetCustomAttributes(typeof(DescriptionAttribute), false); if(attributes != null && attributes.Length > 0) return ((DescriptionAttribute)attributes[0]).Description; } return vrijednost; }
/// <summary> /// Gets the member info of the identifier property for a given entity /// </summary> /// <param name="modelInspector">An instance the model inspector</param> /// <param name="entityType">The type of the entity</param> /// <returns>The member info of the ID property</returns> public static MemberInfo GetIdentifierMember(this IModelInspector modelInspector, Type entityType) { string idPropertyName = GetIdentifierPropertyName(modelInspector, entityType); if (string.IsNullOrEmpty(idPropertyName)) { throw new System.Configuration.ConfigurationErrorsException(string.Format("Missing identifier property. Wrong mapping or missing mapping class for the type {0}", entityType.GetType().FullName)); } return entityType.GetMember(idPropertyName).SingleOrDefault(); }
public static PropertyInfo GetProperty(Type dataobjecttype, string propertyname) { MemberInfo[] members = dataobjecttype.GetMember(propertyname); foreach (MemberInfo member in members) { PropertyInfo property = (member as PropertyInfo); if (property != null) return property; } return null; }
/// <summary> /// Gets the member info of the identifier property for a given entity /// </summary> /// <param name="modelInspector">An instance the model inspector</param> /// <param name="entityType">The type of the entity</param> /// <returns>The member info of the ID property</returns> public static MemberInfo GetIdentifierMember(this IModelInspector modelInspector, Type entityType) { string idPropertyName = GetIdentifierPropertyName(modelInspector, entityType); if (string.IsNullOrEmpty(idPropertyName)) { throw new System.Configuration.ConfigurationErrorsException(string.Format(ExceptionMessages.MemberNotFound, entityType.GetType().FullName)); } return entityType.GetMember(idPropertyName).SingleOrDefault(); }
internal static PropertyInfo GetMatchedPropertyInfo(Type memberType, string[] aryArgName, object[] args) { if (memberType == null) { throw new ArgumentNullException("memberType"); } if (aryArgName == null) { throw new ArgumentNullException("aryArgName"); } if (args == null) { throw new ArgumentNullException("args"); } MemberInfo[][] infoArray5 = new MemberInfo[2][]; infoArray5[0] = memberType.GetDefaultMembers(); MemberInfo[][] infoArray = infoArray5; if (memberType.IsArray) { MemberInfo[] member = memberType.GetMember("Get"); MemberInfo[] infoArray3 = memberType.GetMember("Set"); PropertyInfo info = new ActivityBindPropertyInfo(memberType, member[0] as MethodInfo, infoArray3[0] as MethodInfo, string.Empty, null); infoArray[1] = new MemberInfo[] { info }; } for (int i = 0; i < infoArray.Length; i++) { if (infoArray[i] != null) { MemberInfo[] infoArray4 = infoArray[i]; foreach (MemberInfo info2 in infoArray4) { PropertyInfo propertyInfo = info2 as PropertyInfo; if ((propertyInfo != null) && MatchIndexerParameters(propertyInfo, aryArgName, args)) { return propertyInfo; } } } } return null; }
public static void Sort(this DataGrid dg, Type cTypeOfElement, string sFieldName, bool bBackward) { System.Reflection.PropertyInfo cHeader = (System.Reflection.PropertyInfo)cTypeOfElement.GetMember(sFieldName)[0]; List<ObjectForSort> aOFS = new List<ObjectForSort>(); foreach (object oOFS in dg.ItemsSource) aOFS.Add(new ObjectForSort() { o = oOFS, oValue = cHeader.GetValue(oOFS, null) }); if (bBackward) dg.ItemsSource = aOFS.OrderByDescending(o => o.oValue).Select(o => o.o).ToList(); else dg.ItemsSource = aOFS.OrderBy(o => o.oValue).Select(o => o.o).ToList(); }
public void Merge(Enum ast, System.Type type) { var names = System.Enum.GetNames(type); var values = System.Enum.GetValues(type).Cast <int>().ToArray(); for (int i = 0; i < names.Length; i++) { XmlElement xml = XmlDocReader.XMLFromMember(type.GetMember(names[i]).FirstOrDefault()); ast.Entries.Add(new Enum.Entry(names[i], values[i], xml)); } ast.UnderlyingType = Resolve(System.Enum.GetUnderlyingType(type)); }
static DictionaryParser() { System.Type type = typeof(T); foreach (object enumValue in Enum.GetValues(type)) { MemberInfo memberInfo = type.GetMember(enumValue.ToString())[0]; DictionaryValueAttribute value = (DictionaryValueAttribute)memberInfo.GetCustomAttribute(typeof(DictionaryValueAttribute), false); mappings.Add(value.Input, (T)enumValue); demangledText.Add((T)enumValue, value.Output); startingLetters.Add(value.Input[0]); } }
public static string ToDescription(this System.Enum @enum) { System.Type type = @enum.GetType(); System.Reflection.MemberInfo[] member = type.GetMember(@enum.ToString()); if (member != null && member.Length > 0) { object[] customAttributes = member[0].GetCustomAttributes(typeof(DescriptionAttribute), false); if (customAttributes != null && customAttributes.Length > 0) { return(((DescriptionAttribute)customAttributes[0]).Description); } } return(@enum.ToString()); }
public static string get(System.Enum en) { System.Type type = en.GetType(); MemberInfo[] memInfo = type.GetMember(en.ToString()); if (memInfo != null && memInfo.Length > 0) { object[] attrs = memInfo[0].GetCustomAttributes(typeof(System.ComponentModel.DescriptionAttribute), false); if (attrs != null && attrs.Length > 0) { return(((DescriptionAttribute)attrs[0]).Description); } } return(en.ToString()); }
public System.Type GetPropertyType(string PropertyName) { System.Type dataType = this.DataType; if (dataType != null) { MemberInfo info = dataType.GetMember(PropertyName, BindingFlags.Public | BindingFlags.Instance).FirstOrDefault <MemberInfo>(); if (info is FieldInfo) { return(((FieldInfo)info).FieldType); } if (info is PropertyInfo) { return(((PropertyInfo)info).PropertyType); } } return(null); }
public static string RetornaSistema(sistema.Enum en) { sistema.Type type = en.GetType(); MemberInfo[] memInfo = type.GetMember(en.ToString()); if (memInfo != null && memInfo.Length > 0) { object[] attrs = memInfo[0].GetCustomAttributes(typeof(DescriptionAttribute), false); if (attrs != null && attrs.Length > 0) { return(((DescriptionAttribute)attrs[0]).Description); } } return(en.ToString()); }
public static object InvokeSharedMethod( System.Type type, string method, params object[] parms) { while (type.GetMember(method).GetLength(0) == 0) { type = type.BaseType; if (type == typeof(object)) { type = null; break; } } return(type.InvokeMember(method, System.Reflection.BindingFlags.InvokeMethod, null, null, parms)); }
/// <summary> /// Gets the property value. /// </summary> /// <param name="source">The source.</param> /// <param name="propertyName">Name of the property.</param> /// <param name="mflags">Binding Flags</param> /// <param name="exists">if set to <c>true</c> [exists].</param> /// <returns></returns> public static object GetPropertyValue(object source, string propertyName, BindingFlags mflags, out bool exists) { System.Type sourceType = source.GetType(); MemberInfo[] mmi; foreach (var mfi in sourceType.GetMember(propertyName, mflags).Where(mm => mm != null && mm is PropertyInfo).Select(mm => (PropertyInfo)mm)) { if (mfi.CanRead) { exists = true; return(mfi.GetValue(source, null)); } } exists = false; return(null); }
/// <summary> /// Remove all not requested fields from SQL query /// </summary> /// <typeparam name="TResult">Type of projection type</typeparam> /// <param name="query">nHibernate query</param> /// <param name="keepMembers">List of members names to select</param> /// <returns>Optimized NHibernate query</returns> public static IQueryable <TResult> OptimizeQuery <TResult>(this IQueryable <TResult> query, IReadOnlyCollection <string> keepMembers) { if (query == null) { throw new ArgumentNullException(nameof(query)); } if (keepMembers == null) { throw new ArgumentNullException(nameof(keepMembers)); } if (keepMembers.Count == 0) { throw new ArgumentException("Selected member list should containes at last one field", nameof(keepMembers)); } System.Type type = typeof(TResult); MemberInfo[] members = keepMembers.SelectMany(memberName => type.GetMember(memberName)).ToArray(); return(query.OptimizeQuery(members)); }
/// <summary> /// Set value in object /// </summary> /// <param name="source">The source.</param> /// <param name="propertyName">Name of the property.</param> /// <param name="propertyValue">Set value.</param> /// <returns></returns> public static bool SetValue(object source, string propertyName, object propertyValue) { if (source == null) { return(false); } System.Type sourceType = source.GetType(); BindingFlags mflags = BindingFlags.Public | BindingFlags.SetProperty | BindingFlags.IgnoreCase | BindingFlags.Instance; MemberInfo[] mmi = sourceType.GetMember(propertyName, mflags); foreach (var mfi in mmi.Where(mm => mm != null && mm is PropertyInfo).Select(mm => (PropertyInfo)mm)) { return(SetValuePropertyInfo(source, mfi, propertyValue)); } return(false); }
private void ConfigureFromChildComponentMapping(Property prop, PropertyInfo propInfo) { ConfigureChildComponent( prop, propInfo, (p, pi) => { var attrs = new Attribute[] { new ValidAttribute() }; CreateMemberAttributes(entityType.GetMember(p.Name).FirstOrDefault(), attrs); CreateChildValidator(pi, attrs); }, (tp, component) => { if (!childClassValidators.ContainsKey(tp)) { return; } if (!(childClassValidators[tp] is ClassValidator cv)) { return; } cv.ConfigureFrom(component.PropertyIterator); });
public static object InvokeSharedPropertyGet( System.Type type, string method, params object[] parms) // Static properties are a bit tricky to retrieve. // This is an explicit walk of the hierarchy looking // for the method, assuming if its found the signature // is right. KAD 1/22/04 { while (type.GetMember(method).GetLength(0) == 0) { type = type.BaseType; if (type == typeof(Object)) { type = null; break; } } return(type.InvokeMember(method, System.Reflection.BindingFlags.GetProperty, null, null, parms)); }
/// <summary> /// Remove all not requested fields from select clause /// </summary> /// <typeparam name="TDbObject">Type of database mapped object</typeparam> /// <typeparam name="TResult">Type of projection</typeparam> /// <param name="select">Expression with select clause</param> /// <param name="keepMembers">List of members names to select</param> /// <returns>Optimized NHibernate query</returns> public static Expression <Func <TDbObject, TResult> > OptimizeSelect <TDbObject, TResult>( this Expression <Func <TDbObject, TResult> > select, IReadOnlyCollection <string> keepMembers) { if (select == null) { throw new ArgumentNullException(nameof(select)); } if (keepMembers == null) { throw new ArgumentNullException(nameof(keepMembers)); } if (keepMembers.Count == 0) { throw new ArgumentException("Selected member list should containes at last one field", nameof(keepMembers)); } System.Type type = typeof(TResult); MemberInfo[] members = keepMembers.SelectMany(memberName => type.GetMember(memberName)).ToArray(); return(OptimizeSelect(select, members)); }
internal static List <Enum> EnumGetNonObsoleteValues(this System.Type type) { string[] names = Enum.GetNames(type); Enum[] array = Enum.GetValues(type).Cast <Enum>().ToArray <Enum>(); List <Enum> enumList = new List <Enum>(); for (int index = 0; index < names.Length; ++index) { object[] customAttributes = type.GetMember(names[index])[0].GetCustomAttributes(typeof(ObsoleteAttribute), false); bool flag = false; foreach (object obj in customAttributes) { if (obj is ObsoleteAttribute) { flag = true; } } if (!flag) { enumList.Add(array[index]); } } return(enumList); }
private void CopyComponentValues(Component fromComponent, Component toComponent) { if (fromComponent.GetType() != toComponent.GetType()) { Debug.Log("from " + fromComponent.GetType() + " to " + toComponent.GetType()); Debug.Log("Component type MissMatch!!"); return; } var fromType = fromComponent.GetType(); //フィールドを取得する var bindingFlags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly; MemberInfo[] members = fromType.GetMembers(bindingFlags); foreach (MemberInfo m in members) { if (m.MemberType == MemberTypes.Field) { System.Type fieldType = ((FieldInfo)m).FieldType; Debug.Log("Component:" + fromComponent.GetType() + " type:" + m.MemberType + " fieldType:" + fieldType + ", name:" + m.Name); FieldInfo fieldInfo = toComponent.GetType().GetField(m.Name, bindingFlags); if (fieldInfo != null) { fieldInfo.SetValue(toComponent, fieldInfo.GetValue(fromComponent)); } } else if (m.MemberType == MemberTypes.Property) { System.Type propertyType = ((PropertyInfo)m).PropertyType; Debug.Log("Component:" + fromComponent.GetType() + " type:" + m.MemberType + " propertyType:" + propertyType + ", name:" + m.Name); MemberInfo[] membersGetMethod = propertyType.GetMember("SetValue", bindingFlags); if (fromComponent.GetType() == typeof(UnityEngine.AI.NavMeshAgent)) { //NavMeshAgentはコピーすると動きが不自然だったので対象外にする Debug.Log("not copy " + propertyType); continue; } if ((m.Name != "position") && (m.Name != "rotation") && ((fromComponent.GetType() != typeof(UnityEngine.Animator)) || (m.Name != "runtimeAnimatorController") && (m.Name != "updateMode") && (m.Name != "cullingMode")) && ((fromComponent.GetType() != typeof(UnityEngine.CapsuleCollider)) || (m.Name != "radius") && (m.Name != "height")) && //((fromComponent.GetType() != typeof(UnityEngine.AI.NavMeshAgent)) || (m.Name != "speed") && (m.Name != "angularSpeed") && (m.Name != "acceleration") && (m.Name != "stoppingDistance")) && ((fromComponent.GetType() != typeof(UnityEngine.AudioSource)) || (m.Name != "clip") && (m.Name != "outputAudioMixerGroup") && (m.Name != "playOnAwake")) && (membersGetMethod != null)) { //コピー失敗する可能性があるプロパティを対象外、コピー必要なものは対象外にならないようにする //コピー必要なプロパティが抜けていたら修正する Debug.Log("not copy " + propertyType); continue; } PropertyInfo propertyInfo = toComponent.GetType().GetProperty(m.Name, bindingFlags); if (propertyInfo != null) { propertyInfo.SetValue(toComponent, propertyInfo.GetValue(fromComponent)); } } else { //Debug.Log("Component:" + fromComponent.GetType() + " type:" + m.MemberType + ", name:" + m.Name); } } }
/// <summary> /// Creates inspector field for most basic c# type and returns TRUE if inspector value was changed. /// </summary> /// <param name="label"></param> /// <param name="value"></param> /// <returns></returns> /// Accepted types: /// byte /// sbyte /// short /// ushort /// int /// uint /// long /// float /// double /// bool /// string protected bool MakeInspectorField(string label, ref object value, System.Type containingObjectType = null, bool privateMember = false) { // Returns true if target property or field has the [SerializeField] attribute. bool HasSerializeField() { BindingFlags accessFlag = privateMember ? BindingFlags.NonPublic : BindingFlags.Public; if (containingObjectType != null) { MemberInfo[] allMembers = containingObjectType.GetMembers(); MemberInfo[] memberInfos = containingObjectType.GetMember(label, BindingFlags.Instance | accessFlag); foreach (MemberInfo memberInfo in memberInfos) { SerializeField serializeFieldAttribute = (memberInfo.GetCustomAttribute <SerializeField>(false)); if (serializeFieldAttribute != null) { // Debug.Log("Serialize field attribute found."); return(true); } } return(false); } return(true); } System.Type type = value?.GetType(); if (!HasSerializeField()) { return(false); } if (type == typeof(byte)) { byte oldValue = (byte)value; byte newValue = ByteField(label, (byte)value); value = newValue; return(oldValue != newValue); } if (type == typeof(sbyte)) { sbyte oldValue = (sbyte)value; sbyte newValue = SByteField(label, (sbyte)value); value = newValue; return(oldValue != newValue); } if (type == typeof(short)) { short oldValue = (short)value; short newValue = ShortField(label, (short)value); value = newValue; return(oldValue != newValue); } if (type == typeof(ushort)) { ushort oldValue = (ushort)value; ushort newValue = UShortField(label, (ushort)value); value = newValue; return(oldValue != newValue); } if (type == typeof(int)) { int oldValue = (int)value; int newValue = EditorGUILayout.IntField(label, (int)value); value = newValue; return(oldValue != newValue); } if (type == typeof(uint)) { uint oldValue = (ushort)value; uint newValue = UIntField(label, (uint)value); value = newValue; return(oldValue != newValue); } if (type == typeof(long)) { long oldValue = (long)value; long newValue = EditorGUILayout.LongField(label, (long)value); value = newValue; return(oldValue != newValue); } if (type == typeof(float)) { float oldValue = (float)value; float newValue = EditorGUILayout.FloatField(label, (float)value); value = newValue; return(oldValue != newValue); } if (type == typeof(double)) { double oldValue = (double)value; double newValue = EditorGUILayout.DoubleField(label, (double)value); value = newValue; return(oldValue != newValue); } if (type == typeof(bool)) { bool oldValue = (bool)value; bool newValue = EditorGUILayout.Toggle(label, (bool)value); value = newValue; return(oldValue != newValue); } if (type == typeof(string)) { string oldValue = (string)value; string newValue = EditorGUILayout.TextField(label, (string)value); value = newValue; return(oldValue != newValue); } return(false); }
/// <summary> /// 获取函数的结果 /// </summary> /// <returns></returns> private object GetFunctionResult() { //计算表达式的值 object value = null; List <object> funcParams = new List <object>(); List <Type> funcParamsTypes = new List <Type>(); foreach (IExpression exp in this.FunctionArgs) { object expValue = exp.GetValue(); funcParams.Add(expValue); funcParamsTypes.Add(expValue == null ? typeof(object) : expValue.GetType()); } string invokeMethod = this.Method.GetTextValue(); if (this.Type == null) { //调用自定义函数 UserDefinedFunction func; if (this.OwnerTemplate.UserDefinedFunctions.TryGetValue(invokeMethod, out func)) { value = func(funcParams.ToArray()); } } else { //如果类型定义的是变量表达式则获取表达式的值,否则建立类型 object container = this.Type.Value is VariableExpression?this.Type.Value.GetValue() : Utility.CreateType(this.Type.Value.GetValue().ToString()); if (container != null) { System.Type type = container is System.Type ? (System.Type)container : container.GetType(); BindingFlags flags = BindingFlags.Static | BindingFlags.Public | BindingFlags.IgnoreCase; if (!(container is System.Type)) { flags |= BindingFlags.Instance; } MethodInfo method = type.GetMethod(invokeMethod, flags, null, funcParamsTypes.ToArray(), null); if (method == null) { //获取所有同名的方法 MemberInfo[] methods = type.GetMember(invokeMethod, flags | BindingFlags.InvokeMethod); foreach (MethodInfo m in methods) { ParameterInfo[] parameters = m.GetParameters(); if (parameters.Length == 1 && parameters[0].ParameterType.IsArray && parameters[0].ParameterType.FullName == "System.Object[]") { //如果函数只有一个参数,并且是Object数组参数 try { value = m.Invoke(container is System.Type ? null : container, new object[] { funcParams.ToArray() }); //不出错.则退出查找 break; } catch { } } else if (parameters.Length == funcParams.Count) { //尝试转换类型 List <object> paramValues = new List <object>(); for (var i = 0; i < parameters.Length; i++) { object v = funcParams[i]; if (parameters[i].ParameterType != funcParamsTypes[i] && v != null) { v = Utility.ConvertTo(funcParams[i].ToString(), parameters[i].ParameterType); if (v == null) { break; //转换失败则尝试下一个方法 } paramValues.Add(v); } else { paramValues.Add(v); } } if (paramValues.Count == parameters.Length) { try { value = m.Invoke(container is System.Type ? null : container, paramValues.ToArray()); //不出错.则退出查找 break; } catch { } } paramValues.Clear(); } } } else { //执行方法 try { value = method.Invoke(container is System.Type ? null : container, funcParams.ToArray()); } catch { value = null; } } } } return(value); }
/// <summary> /// This method will set up the Remote Tech object and wrap all the methods/functions /// </summary> /// <returns></returns> public static Boolean InitTRWrapper() { //reset the internal objects _RTWrapped = false; actualRTAPI = null; LogFormatted_DebugOnly("Attempting to Grab Remote Tech Types..."); //find the base type RTAPIType = getType("RemoteTech.API.API"); if (RTAPIType == null) { return(false); } LogFormatted("Remote Tech Version:{0}", RTAPIType.Assembly.GetName().Version.ToString()); //find the RTSettings type RTSettingsType = getType("RemoteTech.RTSettings"); if (RTSettingsType == null) { return(false); } //find the Settings type SettingsType = getType("RemoteTech.Settings"); if (SettingsType == null) { return(false); } //now the RTAntenna Type actualRTAntennaType = getType("RemoteTech.Modules.ModuleRTAntenna"); if (actualRTAntennaType == null) { return(false); } //now grab the running instance LogFormatted_DebugOnly("Got Assembly Types, grabbing Instances"); try { actualRTAPI = RTAPIType.GetMember("HasLocalControl", BindingFlags.Public | BindingFlags.Static); } catch (Exception ex) { LogFormatted("No Remote Tech isInitialised found"); LogFormatted(ex.Message); //throw; } try { actualRTsettings = RTSettingsType.GetField("_instance", BindingFlags.NonPublic | BindingFlags.Static).GetValue(null); } catch (Exception ex) { LogFormatted("No Remote Tech RTSettings Instance found"); LogFormatted(ex.Message); //throw; } if (actualRTAPI == null || actualRTsettings == null) { LogFormatted("Failed grabbing Instance"); return(false); } //If we get this far we can set up the local object and its methods/functions LogFormatted_DebugOnly("Got Instance, Creating Wrapper Objects"); RTactualAPI = new RTAPI(actualRTAPI); _RTWrapped = true; return(true); }
/// <summary> /// Convert object collection to an data table /// </summary> /// <param name="list"></param> /// <returns></returns> public static DataTable ConvertToDataTableFromList(System.Object list) { DataTable dt = null; System.Type listType = list.GetType(); if (listType.IsGenericType) { System.Type type = listType.GetGenericArguments()[0]; dt = new DataTable(type.Name + "List"); MemberInfo[] mems = type.GetMembers(BindingFlags.Public | BindingFlags.Instance); #region 表结构构建 foreach (MemberInfo mem in mems) { //switch(mem.MemberType) //{ // case MemberTypes.Property: // { // dt.Columns.Add(((PropertyInfo)mem).Name,typeof(System.String)); // break; // } // case MemberTypes.Field: // { // dt.Columns.Add(((FieldInfo)mem).Name,typeof(System.String)); // break; // } //} dt.Columns.Add(mem.Name, mem.ReflectedType); } #endregion #region 表数据填充 IList iList = list as IList; foreach (System.Object record in iList) { System.Int32 i = 0; System.Object[] fieldValues = new System.Object[dt.Columns.Count]; foreach (DataColumn dataColumn in dt.Columns) { MemberInfo mem = listType.GetMember(dataColumn.ColumnName)[0]; switch (mem.MemberType) { case MemberTypes.Field: { fieldValues[i] = ((FieldInfo)mem).GetValue(record); break; } case MemberTypes.Property: { fieldValues[i] = ((PropertyInfo)mem).GetValue(record, null); break; } } i++; } dt.Rows.Add(fieldValues); } #endregion } return(dt); }