public static IType InferType(Type type, IMetadataContainer container) { Type genericTypeDefinition = type.GetGenericArguments().Any() ? type.GetGenericTypeDefinition() : type; if (typeof(IFunction<,>).IsAssignableFrom(genericTypeDefinition)) { Type left = type.GetGenericArguments()[0]; Type right = type.GetGenericArguments()[1]; return new Types.ArrowType(InferType(left, container), InferType(right, container)); } else if (typeof(Either<,>).IsAssignableFrom(genericTypeDefinition)) { Type left = type.GetGenericArguments()[0]; Type right = type.GetGenericArguments()[1]; return new Types.SumType(InferType(left, container), InferType(right, container)); } else if (typeof(Tuple<,>).IsAssignableFrom(genericTypeDefinition)) { Type left = type.GetGenericArguments()[0]; Type right = type.GetGenericArguments()[1]; return new Types.ProductType(InferType(left, container), InferType(right, container)); } else if (type.IsGenericParameter) { return new Types.TypeParameter(type.Name); } else { container.ResolveType(type.Name); var genericParameters = type.GetGenericArguments().Select(t => InferType(t, container)).ToArray(); return new Types.TypeSynonym(type.Name, genericParameters); } }
public object Populate(string propertyName, Type propertyType, object currentValue, int depth, Func<int, string, Type, object, PropertyInfo, object> populateKey, Func<int, string, Type, object, PropertyInfo, object> populateValue) { if (currentValue != null && ((IDictionary)currentValue).Count > 0) { return currentValue; } IDictionary newDictionary; if (currentValue != null && ((IDictionary)currentValue).Count == 0) { newDictionary = (IDictionary)currentValue; } else { newDictionary = (IDictionary)Activator.CreateInstance(propertyType); } for (var i = 0; i < AutoBuilderConfiguration.DefaultCollectionItemCount; i++) { newDictionary.Add(populateKey(depth + 1, propertyName, propertyType.GetGenericArguments()[0], null, null), populateValue(depth + 1, propertyName, propertyType.GetGenericArguments()[1], null, null)); } return newDictionary; }
public static SwaggerType GetSwaggerType(Type type) { var swaggerType = new SwaggerType(); //Dig until finding a suitable type if (RegexRecursiveTypes.IsMatch(type.Name.ToLower())) { return GetSwaggerType(type.GetGenericArguments().First()); } if (typeof(IEnumerable<object>).IsAssignableFrom(type) || type.IsArray) { swaggerType.Name = "array"; Type arrayType; if (type.IsGenericType) { arrayType = type.GetGenericArguments().First(); } else { arrayType = type.GetElementType(); } swaggerType.Items = new ItemInfo { Ref = GetTypeName(arrayType) }; swaggerType.type = arrayType; } else { swaggerType.Name = GetTypeName(type); swaggerType.type = type; } return swaggerType; }
private bool IsProperInterface(Type candidateInterface, Type openGenericInterfaceType, Type commandType) { return candidateInterface.IsGenericType && candidateInterface.GetGenericTypeDefinition() == openGenericInterfaceType && candidateInterface.GetGenericArguments().Length == 1 && MatchesType(candidateInterface.GetGenericArguments()[0], commandType); }
/// <summary> /// Gets a correct type definition for a given type, ready for code generation, since /// type.FullName doesnt represent generics in a way to be used in code generation. /// Handles generics. /// Based on: http://stackoverflow.com/questions/401681/how-can-i-get-the-correct-text-definition-of-a-generic-type-using-reflection /// </summary> /// <param name="type">the type to get definition for</param> /// <returns>the string representation of the type definition</returns> public static string GetTypeDefinition(Type type) { if (type.IsGenericParameter) { return type.Name; } if (!type.IsGenericType) { return type.FullName; } StringBuilder builder = new StringBuilder(); string name = type.Name; int index = name.IndexOf("`"); builder.AppendFormat("{0}.{1}", type.Namespace, name.Substring(0, index)); builder.Append('<'); bool first = true; for (int i = 0; i < type.GetGenericArguments().Length; i++) { Type arg = type.GetGenericArguments()[i]; if (!first) { builder.Append(','); } builder.Append(GetTypeDefinition(arg)); first = false; } builder.Append('>'); return builder.ToString(); }
/// <summary> /// Create a new instance from a Type /// </summary> public static object CreateInstance(Type type) { try { CreateObject c = null; if (_cacheCtor.TryGetValue(type, out c)) { return c(); } else { if (type.IsClass) { var dynMethod = new DynamicMethod("_", type, null); var il = dynMethod.GetILGenerator(); il.Emit(OpCodes.Newobj, type.GetConstructor(Type.EmptyTypes)); il.Emit(OpCodes.Ret); c = (CreateObject)dynMethod.CreateDelegate(typeof(CreateObject)); _cacheCtor.Add(type, c); } else if (type.IsInterface) // some know interfaces { if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(IList<>)) { return CreateInstance(GetGenericListOfType(UnderlyingTypeOf(type))); } else if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(IDictionary<,>)) { var k = type.GetGenericArguments()[0]; var v = type.GetGenericArguments()[1]; return CreateInstance(GetGenericDictionaryOfType(k, v)); } else { throw LiteException.InvalidCtor(type); } } else // structs { var dynMethod = new DynamicMethod("_", typeof(object), null); var il = dynMethod.GetILGenerator(); var lv = il.DeclareLocal(type); il.Emit(OpCodes.Ldloca_S, lv); il.Emit(OpCodes.Initobj, type); il.Emit(OpCodes.Ldloc_0); il.Emit(OpCodes.Box, type); il.Emit(OpCodes.Ret); c = (CreateObject)dynMethod.CreateDelegate(typeof(CreateObject)); _cacheCtor.Add(type, c); } return c(); } } catch (Exception) { throw LiteException.InvalidCtor(type); } }
protected override JsonContract CreateContract(Type objectType) { // This class special cases the JsonContract for just the Delta<T> class. All other types should function // as usual. if (objectType.IsGenericType && objectType.GetGenericTypeDefinition() == typeof(Delta<>) && objectType.GetGenericArguments().Length == 1) { var contract = CreateDynamicContract(objectType); contract.Properties.Clear(); var underlyingContract = CreateObjectContract(objectType.GetGenericArguments()[0]); var underlyingProperties = underlyingContract.CreatedType.GetProperties(BindingFlags.Public | BindingFlags.Instance); foreach (var property in underlyingContract.Properties) { property.DeclaringType = objectType; property.ValueProvider = new DynamicObjectValueProvider() { PropertyName = this.ResolveName(underlyingProperties, property.PropertyName), }; contract.Properties.Add(property); } return contract; } return base.CreateContract(objectType); }
/// <summary> /// 获取配置项的值的类型的枚举 /// </summary> /// <param name="valType">配置项值类型</param> /// <returns></returns> public static string GetConfigItemValueTypeEnum(Type valType) { //列表 if (typeof(IList).IsAssignableFrom(valType)) { var genericArguments = valType.GetGenericArguments(); if (genericArguments.Length == 1 && valType.IsGenericType && genericArguments.First() == typeof(object)) return ValueTypeEnum.ObjectItemList.ToString(); return ValueTypeEnum.List.ToString(); } //字典 if (typeof(IDictionary).IsAssignableFrom(valType)) { var genericArguments = valType.GetGenericArguments(); if (genericArguments.Length == 2 && genericArguments.First() == typeof(string) && valType.IsGenericType && genericArguments.Last() == typeof(object)) return ValueTypeEnum.ObjectItemDictionary.ToString(); return ValueTypeEnum.Dictionary.ToString(); } //基础类型 if (IsUnderlyingType(valType)) { return ValueTypeEnum.Underlying.ToString(); } //自定义配置实体 return ValueTypeEnum.Entity.ToString(); }
public static Item Create(Type type) { if (type == typeof(string)) { return new StringItem(); } if (type == typeof(float)) { return new FloatItem(); } if (type == typeof(double)) { return new DoubleItem(); } else if (type.GetCustomAttributes(typeof(CubeHack.Data.EditorDataAttribute), false).Length != 0) { return new ObjectItem(type); } else if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Dictionary<,>) && type.GetGenericArguments()[0] == typeof(string)) { return new DictionaryItem(type.GetGenericArguments()[1]); } else if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(List<>)) { return new ListItem(type.GetGenericArguments()[0]); } else { throw new ArgumentException("type"); } }
public object CreateInstance(Type type, string name) { if (type.IsArray) { return CreateArray(type); } if (type.IsGenericType) { Type genericType = type.GetGenericTypeDefinition(); if (genericType == typeof(IEnumerable<>) || genericType == typeof(ICollection<>) || genericType == typeof(IList<>) || genericType == typeof(List<>)) { Type argument = type.GetGenericArguments().Single(); return CreateListFromElement(argument); } if (genericType == typeof(ISet<>) || genericType == typeof(HashSet<>)) { Type argument = type.GetGenericArguments().Single(); return CreateSetFromElement(argument); } if (genericType == typeof(IDictionary<,>) || genericType == typeof(Dictionary<,>)) { Type[] arguments = type.GetGenericArguments(); return CreateDictionaryFromElements(arguments[0], arguments[1]); } } throw new InvalidOperationException("Unsupported Collection. You need to specify a custom builder."); }
static string GenericTypeName(Type type) { if (!type.IsGenericType) return null; Type typedef = type.GetGenericTypeDefinition(); if (typedef == typeof (Nullable<>)) return Get(type.GetGenericArguments().Single()) + "?"; var typeArgs = type.GetGenericArguments(); var typeArgIdx = typeArgs.Length; var revNestedTypeNames = new List<string>(); while (type != null) { var name = type.Name; var backtickIdx = name.IndexOf('`'); if (backtickIdx < 0) revNestedTypeNames.Add(name); else { var thisTypeArgCount = int.Parse(name.Substring(backtickIdx + 1)); var argsNames = new List<string>(); for (int i = typeArgIdx - thisTypeArgCount; i < typeArgIdx; i++) argsNames.Add(Get(typeArgs[i])); typeArgIdx -= thisTypeArgCount; revNestedTypeNames.Add(name.Substring(0, backtickIdx) + "<" + string.Join(", ", argsNames) + ">"); } type = type.DeclaringType; } revNestedTypeNames.Reverse(); return string.Join(".", revNestedTypeNames); }
private IDictionary DeserializeToDictionary(string input, Type type) { if (input.StartsWith("{", StringComparison.Ordinal) == true && input.EndsWith("}", StringComparison.Ordinal) == true) { string source = input; input = input.Substring(1, input.Length - 2); IDictionary dictionary = Activator.CreateInstance(type, true) as IDictionary; // 获取键类型。 Type keyType = type.GetGenericArguments()[0]; // 获取值类型。 Type valueType = type.GetGenericArguments()[1]; foreach (var temp in JsonHelper.ItemReader(input)) { string key; string value; JsonHelper.ItemSpliter(temp, out key, out value); object oKey = DeserializeToObject(key, keyType); if (dictionary.Contains(oKey) == false) { object oValue = DeserializeToObject(value, valueType); dictionary.Add(oKey, oValue); } else { throw new JsonDeserializeException(source, type); } } return dictionary; } else { throw new JsonDeserializeException(input, type); } }
public Type GetActualType(Type type, IAdviceRequester adviceRequester) { Type result = null; if (type != null) { if (type != typeof(string)) { if (!typeof(IDictionary).IsAssignableFrom(type) && (!type.IsGenericType || type.GetGenericArguments().Length != 2 || !typeof(IDictionary<,>).MakeGenericType(type.GetGenericArguments()).IsAssignableFrom(type))) { if (type.IsClass && typeof(IEnumerable).IsAssignableFrom(type)) result = type; else { if (type.IsInterface && type.IsAssignableFrom(typeof(List<object>))) result = typeof(List<object>); else { if (type.IsGenericType && type.GetGenericArguments().Length == 1 && type.IsAssignableFrom(typeof(List<>).MakeGenericType(type.GetGenericArguments()))) result = typeof(List<>).MakeGenericType(type.GetGenericArguments()); } } } } } if (_log.IsDebugEnabled) _log.Debug("Converted '" + type + "' to '" + result + "'."); return result; }
public string Get(Type type) { definitions.Clear(); Types.Clear(); string schema; if (type.IsGenericType && TypeBuilderHelper.IsGenericWebResult(type)) type = type.GetGenericArguments()[0]; if (TypeBuilderHelper.IsArrayOrEnumerable(type)) { var elementType = type.GetElementType() ?? type.GetGenericArguments()[0]; if (elementType.GetProperties().Count(p => p.CanRead || p.CanWrite) == 0) return null; schema = GetArray(elementType); } else { if (type.GetProperties().Count(p => p.CanRead || p.CanWrite) == 0) return null; schema = GetMainObjectSchema(type); } schema = AddDefinitionsIfAny(schema); schema += "}" + Environment.NewLine; return schema; }
/// <summary> /// 生成类定义 /// </summary> /// <param name="type">类型</param> /// <param name="isPartial">是否部分定义</param> /// <param name="isClass">是否建立类定义</param> private void create(Type type, bool isPartial, bool isClass) { if (type.ReflectedType == null) { start.Add("namespace " + type.Namespace + @" {"); end.Add(@" }"); } else { create(type.ReflectedType.IsGenericType ? type.ReflectedType.MakeGenericType(type.GetGenericArguments()) : type.ReflectedType, true, true); } if (isClass) { start.Add(@" " + (type.IsPublic ? "public" : null) + (type.IsAbstract ? " abstract" : null) + (isPartial ? " partial" : null) + (type.IsInterface ? " interface" : " class") + " " + type.Name + (type.IsGenericType ? "<" + type.GetGenericArguments().joinString(", ", x => x.fullName()) + ">" : null) + @" {"); end.Add(@" }"); } }
/// <summary> /// Gets the type of the dictionary. /// </summary> /// <param name = "type">The type.</param> /// <returns></returns> public IDictionaryAdapter GetDictionaryAdapter(Type type) { DictionaryTypeFactoryDelegate factory; if(DictionaryTypes.TryGetValue(type, out factory)) return factory(); if(type.IsGenericType && !type.IsGenericTypeDefinition) { var genericType = type.GetGenericTypeDefinition(); if(genericType == typeof(SortedList<,>)) { var genericArgs = type.GetGenericArguments(); var adapterType = typeof(GenericSortedListDictionaryAdapter<,>).MakeGenericType(genericArgs[0], genericArgs[1]); return (IDictionaryAdapter)Activator.CreateInstance(adapterType); } if(genericType == typeof(IDictionary<,>) || genericType == typeof(Dictionary<,>)) { var genericArgs = type.GetGenericArguments(); var adapterType = typeof(GenericDictionaryDictionaryAdapter<,>).MakeGenericType(genericArgs[0], genericArgs[1]); return (IDictionaryAdapter)Activator.CreateInstance(adapterType); } } return null; }
public static bool IsGenericAssignableFrom(Type t, Type other) { if (other.GetGenericArguments().Length != t.GetGenericArguments().Length) return false; var genericT = t.MakeGenericType(other.GetGenericArguments()); return genericT.IsAssignableFrom(other); }
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { if (reader.TokenType == JsonToken.Null) return null; var keyType = objectType.GetGenericArguments()[0]; var keyValueType = keyType.BaseType.GetGenericArguments()[0]; var valueType = objectType.GetGenericArguments()[1]; var intermediateDictionaryType = typeof(Dictionary<,>).MakeGenericType(typeof(string), valueType); var intermediateDictionary = (IDictionary)Activator.CreateInstance(intermediateDictionaryType); serializer.Populate(reader, intermediateDictionary); var valueProperty = keyType.GetProperty("Value"); var finalDictionary = (IDictionary)Activator.CreateInstance(objectType); foreach (DictionaryEntry pair in intermediateDictionary) { object value; if (keyValueType == typeof(Guid)) value = Guid.Parse(pair.Key.ToString()); else value = Convert.ChangeType(pair.Key, keyValueType, null); var key = Activator.CreateInstance(keyType); valueProperty.SetValue(key, value, null); finalDictionary.Add(key, pair.Value); } return finalDictionary; }
public static void TestAndAddRecursive(Type type, String declaringTypeNamespace, List<Type> valueTypes, List<String> namespaces) { if (type.IsGenericType) { if (type.GetGenericArguments() != null) { foreach (var genericArg in type.GetGenericArguments()) { TestAndAddRecursive(genericArg, declaringTypeNamespace, valueTypes, namespaces); } } return; } if (IsValueTypeNoEnumOrPrimitve(type) && !valueTypes.Contains(type) && type.Namespace != "System" && type.Namespace != declaringTypeNamespace) { valueTypes.Add(type); } if (!IsValueTypeNoEnumOrPrimitve(type) && type.Namespace != declaringTypeNamespace) { if (!ExcludedExternalNamespaces.Contains(type.Namespace) && !namespaces.Contains(type.Namespace)) { namespaces.Add(type.Namespace); } else if (type.Namespace == "System" && type.Name == "Uri" && !namespaces.Contains("Windows.Foundation")) // Uri is special.. { namespaces.Add("Windows.Foundation"); } } }
private string GetMEFContractName(Type type) { var name = new StringBuilder(); if (!string.IsNullOrEmpty(type.Namespace)) { name.Append(type.Namespace); name.Append("."); } var strippedName = type.Name; if (type.Name.Contains("`")) { strippedName = type.Name.Substring(0, strippedName.IndexOf("`")); } name.Append(strippedName); if (type.GetGenericArguments().Length > 0) { name.Append("("); name.Append(string.Join(",", type.GetGenericArguments().Select(GetMEFContractName))); name.Append(")"); } return name.ToString(); }
public virtual bool CanParseType(Type type) { return type.IsKeyValuePairType() && StringParsing.GetParser(type.GetGenericArguments()[0]) != null && StringParsing.GetParser(type.GetGenericArguments()[1]) != null; }
private DictionaryJsonSerializer(Type type, bool encrypt, JsonMappings mappings, bool shouldUseAttributeDefinedInInterface) { _encrypt = encrypt; _mappings = mappings; _shouldUseAttributeDefinedInInterface = shouldUseAttributeDefinedInInterface; Type keyType; if (type.IsAssignableToGenericIDictionary()) { var genericArguments = type.GetGenericArguments(); keyType = genericArguments[0]; if (typeof(IDictionary<string, object>).IsAssignableFrom(type)) { _valueSerializer = JsonSerializerFactory.GetSerializer(genericArguments[1], _encrypt, _mappings, shouldUseAttributeDefinedInInterface); _write = GetIDictionaryOfStringToObjectWriteAction(); } else if (type.IsAssignableToGenericIDictionaryOfStringToAnything()) { _valueSerializer = JsonSerializerFactory.GetSerializer(genericArguments[1], _encrypt, _mappings, shouldUseAttributeDefinedInInterface); _write = GetIDictionaryOfStringToAnythingWriteAction(); } else { _keySerializer = JsonSerializerFactory.GetSerializer(genericArguments[0], _encrypt, _mappings, shouldUseAttributeDefinedInInterface); _valueSerializer = JsonSerializerFactory.GetSerializer(genericArguments[1], _encrypt, _mappings, shouldUseAttributeDefinedInInterface); _write = GetIDictionaryOfAnythingToAnythingWriteAction(); } } else { keyType = typeof(object); _keySerializer = JsonSerializerFactory.GetSerializer(typeof(object), _encrypt, _mappings, shouldUseAttributeDefinedInInterface); _valueSerializer = _keySerializer; _write = GetIDictionaryOfAnythingToAnythingWriteAction(); } if (type.IsInterface) { if (type.IsGenericIDictionary()) { type = typeof(Dictionary<,>).MakeGenericType( type.GetGenericArguments()[0], type.GetGenericArguments()[1]); } else if (type == typeof(IDictionary)) { type = typeof(Dictionary<object, object>); } else { throw new NotSupportedException(type.FullName); } } _createDictionary = GetCreateDictionaryFunc(type); _deserializeKey = GetDeserializeKeyFunc(keyType); _addToDictionary = GetAddToDictionaryAction(type); }
public static string GetFullName(Type type) { if (type.IsByRef) return "ref " + GetFullName(type.GetElementType()); if (type.DeclaringType != null) return GetFullName(type.DeclaringType) + "." + TypeName(type); // HACK: Some constructed generic types report a FullName of null if (type.FullName == null) { string[] argumentNames = Array.ConvertAll<Type, string>( type.GetGenericArguments(), GetFullName); return string.Format( "{0}[{1}]", GetFullName(type.GetGenericTypeDefinition()), string.Join(", ", argumentNames)); } string name = TypeName(type.FullName); if (type.IsGenericTypeDefinition) { name = string.Format( "{0}[of {1}]", name, string.Join(", ", Array.ConvertAll<Type, string>( type.GetGenericArguments(), TypeName))); } return name; }
void CheckDoesModelTypeMatch(Type type, Type modelType) { if (type.IsGenericType) { if (type.GetGenericTypeDefinition() == typeof(View<>)) { if (modelType == null) { throw new InvalidOperationException(string.Format("The strongly typed view {0} expects a model type of {1} but was passed null.", ViewFile, type.GetGenericArguments()[0])); } if (!type.GetGenericArguments()[0].IsAssignableFrom(modelType)) { throw new InvalidOperationException(string.Format("The strongly typed view {0} expects a model type of {1} but was passed model of type {2}.", ViewFile, type.GetGenericArguments()[0], modelType)); } return; } } if (type == typeof(View)) return; // Recurse CheckDoesModelTypeMatch(type.BaseType, modelType); }
public static bool TryApplyRule(Type sourceType, Type destinationType, out IMemberMappingRule rule) { rule = null; //check that it is a class and not an array as arrays should be handled by other rule if (!destinationType.IsClass || destinationType.IsArray || !sourceType.IsClass || sourceType.IsArray) return false; //it source and the destinations must implement IEnumerable if (!destinationType.GetInterfaces().Contains(typeof(System.Collections.IEnumerable)) || !sourceType.GetInterfaces().Contains(typeof(System.Collections.IEnumerable))) return false; //and must have one generic type parameter (that will exclude dictionaries and othe special //IEnumerable implementations) if (destinationType.GetGenericArguments().Count() != 1 || sourceType.GetGenericArguments().Count() != 1) return false; Type genericSourceType = sourceType.GetGenericArguments().Single(); Type genericDestinationType = destinationType.GetGenericArguments().Single(); IMemberMappingRule innerRule; bool canMapGenerics = RuleProvider.GetApplicableRule(genericSourceType, genericDestinationType, out innerRule); if (canMapGenerics) { rule = new EnumerableRule(sourceType, destinationType, innerRule); } return canMapGenerics; }
/// <summary> /// Get a function that coerces a sequence of one type into another type. /// This is primarily used for aggregators stored in ProjectionExpression's, which are used to represent the /// final transformation of the entire result set of a query. /// </summary> public static LambdaExpression GetAggregator(Type expectedType, Type actualType) { Type actualElementType = TypeHelper.GetElementType(actualType); if (!expectedType.IsAssignableFrom(actualType)) { Type expectedElementType = TypeHelper.GetElementType(expectedType); ParameterExpression p = Expression.Parameter(actualType, "p"); Expression body = null; if (expectedType.IsAssignableFrom(actualElementType)) { body = Expression.Call(typeof(Enumerable), "SingleOrDefault", new Type[] { actualElementType }, p); } else if (expectedType.IsGenericType && (expectedType == typeof(IQueryable) || expectedType == typeof(IOrderedQueryable) || expectedType.GetGenericTypeDefinition() == typeof(IQueryable<>) || expectedType.GetGenericTypeDefinition() == typeof(IOrderedQueryable<>))) { body = Expression.Call( typeof(Queryable), "AsQueryable", new Type[] { expectedElementType }, CoerceElement(expectedElementType, p)); if (body.Type != expectedType) { body = Expression.Convert(body, expectedType); } } else if (expectedType.IsArray && expectedType.GetArrayRank() == 1) { body = Expression.Call( typeof(Enumerable), "ToArray", new Type[] { expectedElementType }, CoerceElement(expectedElementType, p)); } else if (expectedType.IsGenericType && expectedType.GetGenericTypeDefinition().IsAssignableFrom(typeof(IList<>))) { var gt = typeof(DeferredList<>).MakeGenericType(expectedType.GetGenericArguments()); var cn = gt.GetConstructor(new Type[] { typeof(IEnumerable<>).MakeGenericType(expectedType.GetGenericArguments()) }); body = Expression.New(cn, CoerceElement(expectedElementType, p)); } else if (expectedType.IsAssignableFrom(typeof(List<>).MakeGenericType(actualElementType))) { // List<T> can be assigned to expectedType body = Expression.Call( typeof(Enumerable), "ToList", new Type[] { expectedElementType }, CoerceElement(expectedElementType, p)); } else { // some other collection type that has a constructor that takes IEnumerable<T> ConstructorInfo ci = expectedType.GetConstructor(new Type[] { actualType }); if (ci != null) { body = Expression.New(ci, p); } } if (body != null) { return Expression.Lambda(body, p); } } return null; }
public override bool CanConvert(Type objectType) { // For some reason, JSON.NET doesn't call converters on dictionary keys! So we have to hijack the entire dictionary. return objectType.IsGenericType && objectType.GetGenericTypeDefinition() == typeof(Dictionary<,>) && objectType.GetGenericArguments()[0].IsEnum && !objectType.GetGenericArguments()[0].GetCustomAttributes(typeof(FlagsAttribute), false).Any(); }
public static IList<Type> GetTupleItemTypes( Type tupleType ) { Contract.Assert( tupleType.Name.StartsWith( "Tuple`" ) && tupleType.GetAssembly().Equals( typeof( Tuple ).GetAssembly() ) ); var arguments = tupleType.GetGenericArguments(); List<Type> itemTypes = new List<Type>( tupleType.GetGenericArguments().Length ); GetTupleItemTypes( arguments, itemTypes ); return itemTypes; }
public KeyValuePairSerializer(Serializers s, Type type) { getKey = type.DelegateForGetPropertyValue ("Key"); getValue = type.DelegateForGetPropertyValue ("Value"); key = s.FromDeclared (type.GetGenericArguments()[0]); value = s.FromDeclared (type.GetGenericArguments()[1]); newObj = type.DelegateForCreateInstance (type.GetGenericArguments ()); }
internal static Property ConvertTypeToProperty(Type type) { Property property = new Property(); property.Type = type; property.Name = type.Name; property.IsClass = type.IsClass; property.IsEnum = type.IsEnum; property.IsByteArray = type == typeof(byte[]); property.IsGuid = (type == typeof(Guid) || type == typeof(Guid?)); property.IsDateTime = type == typeof(DateTime) || type == typeof(DateTime?); property.IsInt = type == typeof(int) || type == typeof(int?); property.IsLong = type == typeof(long) || type == typeof(long?); property.IsString = type == typeof(string); property.IsBool = type == typeof(bool) || type == typeof(bool?); property.IsGenericType = type.IsGenericType; if (property.IsGenericType) { property.ElementType = type.GetGenericArguments()[0]; } property.IsArray = type.IsArray; if (property.IsArray) { property.ElementType = type.GetElementType(); } property.IsDictionary = type.Name.Contains("Dictionary"); if (property.IsDictionary) { property.GenericTypes = type.GetGenericArguments(); } if (property.IsDictionary && property.GenericTypes[0] == typeof(string) && property.GenericTypes[1] == typeof(string)) { property.IsStringDictionary = true; } property.IsValueType = type.IsValueType; if (type.IsGenericType && type.GetGenericTypeDefinition().Equals(typeof(Nullable<>))) { property.IsNullable = true; property.ValueType = type.GetGenericArguments()[0]; } else { property.ValueType = type; } return property; }
protected void Init_HasToggle() { System.Type pType_InterfaceHasToggle = this.GetType().GetInterfaces().FirstOrDefault(x => x.IsGenericType && x.GetGenericTypeDefinition() == typeof(IUIObject_HasToggle <>));; if (pType_InterfaceHasToggle != null) { System.Type pType_EnumButtonName = pType_InterfaceHasToggle.GetGenericArguments()[0]; var pMethod = pType_InterfaceHasToggle.GetMethod("IUIObject_HasToggle_OnToggle"); Toggle[] arrToggle = GetComponentsInChildren <Toggle>(true); for (int i = 0; i < arrToggle.Length; i++) { Toggle pToggle = arrToggle[i]; bool bParseSuccess = true; object pEnum = null; Parsing_NameToEnum(pType_EnumButtonName, pToggle, out bParseSuccess, out pEnum); if (bParseSuccess) { UnityEngine.Events.UnityAction <bool> pButtonAction = delegate(bool bIsOn) { pMethod.Invoke(this, new object[3] { pEnum, pToggle, bIsOn }); }; pToggle.onValueChanged.RemoveListener(pButtonAction); pToggle.onValueChanged.AddListener(pButtonAction); } } } }
// ========================================================================== // #region Private /* private - [Proc] Function * 로직을 처리(Process Local logic) */ /* private - Other[Find, Calculate] Func * 찾기, 계산등 단순 로직(Simpe logic) */ protected void Init_HasButton() { System.Type pType_InterfaceHasButton = this.GetType().GetInterfaces().FirstOrDefault(x => x.IsGenericType && x.GetGenericTypeDefinition() == typeof(IUIObject_HasButton <>));; if (pType_InterfaceHasButton != null) { System.Type pType_EnumButtonName = pType_InterfaceHasButton.GetGenericArguments()[0]; var pMethod = pType_InterfaceHasButton.GetMethod("IUIObject_HasButton_OnClickButton"); Button[] arrButton = GetComponentsInChildren <Button>(true); for (int i = 0; i < arrButton.Length; i++) { Button pButton = arrButton[i]; bool bParseSuccess; object pEnum; Parsing_NameToEnum(pType_EnumButtonName, pButton, out bParseSuccess, out pEnum); if (bParseSuccess) { UnityEngine.Events.UnityAction pButtonAction = delegate { pMethod.Invoke(this, new object[2] { pEnum, pButton }); }; pButton.onClick.RemoveListener(pButtonAction); pButton.onClick.AddListener(pButtonAction); } } } }
private static string TypeDecl(System.Type t) { if (t.IsGenericType) { string ret = GenericBaseName(t); string gs = ""; gs += "<"; System.Type[] types = t.GetGenericArguments(); for (int n = 0; n < types.Length; n++) { gs += SimpleName(types[n]); if (n < types.Length - 1) { gs += ","; } } gs += ">"; ret = Regex.Replace(ret, @"`\d+", gs); return(ret); } if (t.IsArray) { return(TypeDecl(t.GetElementType()) + "[]"); } else { return(RemoveRef(t.ToString(), false)); } }
public static string GetFriendlyName(this System.Type type) { if (type == null) { return(""); } string friendlyName = type.Name; if (type.IsGenericType) { int iBacktick = friendlyName.IndexOf('`'); if (iBacktick > 0) { friendlyName = friendlyName.Remove(iBacktick); } friendlyName += "<"; System.Type[] typeParameters = type.GetGenericArguments(); for (int i = 0; i < typeParameters.Length; ++i) { string typeParamName = GetFriendlyName(typeParameters[i]); friendlyName += (i == 0 ? typeParamName : "," + typeParamName); } friendlyName += ">"; } return(friendlyName); }
public static void Write(BinaryWriter writer, System.Type type) { if (type == null) { writer.Write((byte)0xFF); return; } if (type.IsGenericType) { var t = type.GetGenericTypeDefinition(); var p = type.GetGenericArguments(); writer.Write((byte)p.Length); writer.Write(t.AssemblyQualifiedName); for (int i = 0; i < p.Length; i++) { Write(writer, p[i]); } return; } writer.Write((byte)0); writer.Write(type.AssemblyQualifiedName); }
public override void execute(Data data) { Dialog dialog = GameManager.Instance.DialogServer.dialogGet(DialogID); System.Type dialogType = dialog.GetType().BaseType; System.Type[] genericTypes = dialogType.GetGenericArguments(); //DialogSetting setting = Settings.ToObject <genericTypes[0]> (); DialogSetting setting = (DialogSetting)JsonConvert.DeserializeObject(Settings.ToString(), genericTypes[0]); GameManager.Instance.DialogServer.dialogShow(dialog, setting); }
System.Type GetFieldType() { System.Type type = fieldInfo.FieldType; if (type.IsArray) { type = type.GetElementType(); } else if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(List <>)) { type = type.GetGenericArguments()[0]; } return(type); }
public override bool CanConvert(System.Type objectType) { var isGenericList = objectType.IsGenericType && objectType.GetGenericTypeDefinition() == typeof(List <>); if (isGenericList) { var contentIsUnityObject = objectType.GetGenericArguments()[0].IsSubclassOf(typeof(UnityEngine.Object)); if (contentIsUnityObject) { return(true); } } return(false); }
private static Maybe <object> ChangeType(IEnumerable <string> values, System.Type conversionType, CultureInfo conversionCulture) { var type = conversionType.GetGenericArguments() .SingleOrDefault() .ToMaybe() .FromJust( new ApplicationException("Non scalar properties should be sequence of type IEnumerable<T>.")); var converted = values.Select(value => ChangeType(value, type, conversionCulture)); return(converted.Any(a => a.MatchNothing()) ? Maybe.Nothing <object>() : Maybe.Just(converted.Select(c => ((Just <object>)c).Value).ToArray(type))); }
static string GetTypeFullName(System.Type refType) { if (refType.IsConstructedGenericType) { string baseName = refType.GetGenericTypeDefinition().FullName; baseName = baseName.Substring(0, baseName.IndexOf('`')); string arguments = String.Join(", ", refType.GetGenericArguments().Select(t => GetTypeFullName(t))); return($"{baseName}<{arguments}>"); } else { return(refType.FullName); } }
private static OpenApiReference BuildReference(IDictionary <string, OpenApiSchema> schemas, Type type) { var name = type.IsGenericType ? ToCamelCase(string.Join("|", new[] { type.Name }.Union(type.GetGenericArguments().Select(x => x.Name)))) : ToCamelCase(type.Name); if (schemas.TryGetValue(name, out var schema)) { return(new OpenApiReference { Id = name, Type = ReferenceType.Schema }); } var properties = type.GetProperties(BindingFlags.Instance | BindingFlags.Public); var props = properties .Select(x => { var propertyType = x.PropertyType; if (_primitiveTypeMap.ContainsKey(propertyType)) { return(new SchemaName { Name = ToCamelCase(x.Name), Schema = _primitiveTypeMap[propertyType]() }); } var swaggerDataType = ToSwaggerDataType(propertyType); return(GetSchema(schemas, swaggerDataType, propertyType, x)); }) .ToDictionary(x => x.Name, x => x.Schema); schema = new OpenApiSchema { Type = "object", Properties = props }; schemas.Add(name, schema); return(new OpenApiReference { Id = name, Type = ReferenceType.Schema }); }
public override object GetValue() { System.Type runtimeType = decorator.runtimeType; System.Type[] itemTypes = runtimeType.GetGenericArguments(); object[] items = GetItemValues(itemTypes[0]); object obj = Activator.CreateInstance(runtimeType); BindingFlags flag = BindingFlags.Instance | BindingFlags.Public; MethodInfo methodInfo = runtimeType.GetMethod("Add", flag); for (int i = 0; i < items.Length; i++) { methodInfo.Invoke(obj, new object[] { items[i] }); } return(obj); }
private static bool TryGetMapFieldTypes(Type type, out IEnumerable <Type> types) { types = null; if (!type.GetTypeInfo().IsGenericType) { return(false); // not MapField } var genTypeDef = type.GetGenericTypeDefinition(); if (genTypeDef != typeof(MapField <,>)) { return(false); // not MapField } types = type.GetGenericArguments(); return(true); }
public virtual System.Type GetElementType(System.Type p_type) { System.Type v_returnedType = null; if (p_type != null) { if (p_type.IsArray) { v_returnedType = p_type.GetElementType(); } else if (Kyub.Extensions.TypeExtensions.IsSameOrSubClassOrImplementInterface(p_type, typeof(IArrayList))) { v_returnedType = p_type; string v_typeSafeName = v_returnedType != null ? v_returnedType.FullName : ""; while (v_returnedType != null && !v_typeSafeName.Contains("ArrayList`1")) { v_returnedType = v_returnedType.BaseType; v_typeSafeName = v_returnedType != null ? v_returnedType.FullName : ""; } try { v_returnedType = v_returnedType.GetGenericArguments()[0]; } catch { v_returnedType = null; } } else { System.Type[] v_interfaceTypes = p_type.GetInterfaces(); foreach (System.Type v_interfaceType in v_interfaceTypes) { string v_interfaceSafeName = v_interfaceType != null ? v_interfaceType.FullName : ""; //SerializableTypeCache.GetSafeTypedNameInAssembly(v_interfaceType); if (v_interfaceSafeName.Contains("IList`1") || v_interfaceSafeName.Contains("ICollection`1") || v_interfaceSafeName.Contains("IEnumerable`1")) { try { v_returnedType = v_interfaceType.GetGenericArguments()[0]; break; } catch { } } } } } return(v_returnedType); }
public static void AddFaultDescription(Receive activity, OperationDescription operation) { if (activity.HasFault) { foreach (SendReply reply in activity.FollowingFaults) { string overridingAction = null; System.Type internalDeclaredMessageType = null; overridingAction = reply.Action; SendMessageContent internalContent = reply.InternalContent as SendMessageContent; if (internalContent != null) { internalDeclaredMessageType = internalContent.InternalDeclaredMessageType; } else { SendParametersContent content2 = reply.InternalContent as SendParametersContent; if (content2 != null) { internalDeclaredMessageType = content2.ArgumentTypes[0]; } } if (internalDeclaredMessageType.IsGenericType && (internalDeclaredMessageType.GetGenericTypeDefinition() == FaultExceptionType)) { System.Type faultType = internalDeclaredMessageType.GetGenericArguments()[0]; bool flag = false; foreach (FaultDescription description in operation.Faults) { if (description.DetailType == faultType) { if (description.Action != overridingAction) { throw System.ServiceModel.Activities.FxTrace.Exception.AsError(new ValidationException(System.ServiceModel.Activities.SR.SendRepliesHaveSameFaultTypeDifferentAction)); } flag = true; break; } } if (!flag) { FaultDescription item = MessageBuilder.CreateFaultDescription(operation, faultType, overridingAction); operation.Faults.Add(item); } } } } }
/// <summary> /// Register serializer for ValueTuples /// </summary> private SerializerPair CreateValueTupleSerializer <T>() { TypeInfo typeInfo = typeof(T).GetTypeInfo(); ReflectionSerializerVerifier.AssertRoot(typeInfo); var argumentTypes = typeInfo.GetGenericArguments(); var memberGetters = typeInfo.GetFields().Select(ReflectionUtil.GetGetter).ToArray(); var memberDeserializers = new CtxReadDelegate <object> [argumentTypes.Length]; var memberSerializers = new CtxWriteDelegate <object> [argumentTypes.Length]; for (var index = 0; index < argumentTypes.Length; index++) { var argumentType = argumentTypes[index]; var serPair = GetOrRegisterSerializerInternal(argumentType); memberDeserializers[index] = ConvertReader(argumentType, serPair.Reader); memberSerializers[index] = ConvertWriter(argumentType, serPair.Writer); } var type = typeInfo.AsType(); CtxReadDelegate <T> readerDelegate = (ctx, unsafeReader) => { // todo: consider using IL emit var activatorArgs = new object[argumentTypes.Length]; for (var index = 0; index < argumentTypes.Length; index++) { var value = memberDeserializers[index](ctx, unsafeReader); activatorArgs[index] = value; } var instance = Activator.CreateInstance(type, activatorArgs); return((T)instance); }; CtxWriteDelegate <T> writerDelegate = (ctx, unsafeWriter, value) => { for (var i = 0; i < argumentTypes.Length; i++) { var memberValue = memberGetters[i](value); memberSerializers[i](ctx, unsafeWriter, memberValue); } }; return(new SerializerPair(readerDelegate, writerDelegate)); }
public static System.Type DetermineCollectionElementType(this System.Type genericCollection) { List <System.Type> interfaces = genericCollection.GetInterfaces().Where(t => t.IsGenericType).ToList(); if (genericCollection.IsGenericType) { interfaces.Add(genericCollection); } System.Type enumerableInterface = interfaces.FirstOrDefault(t => t.GetGenericTypeDefinition() == typeof(IEnumerable <>)); if (enumerableInterface != null) { return(enumerableInterface.GetGenericArguments()[0]); } return(null); }
/// <summary> /// Returns an <see cref="T:System.Object"/> with the specified <see cref="T:System.Type"/> /// and whose value is equivalent to the specified object. /// </summary> /// <param name="value">An <see cref="T:System.Object"/> that implements the <see cref="T:System.IConvertible"/> interface.</param> /// <param name="conversionType">A <see cref="T:System.Type"/>.</param> /// <returns>An object whose <see cref="T:System.Type"/> is conversionType and whose value is equivalent /// to value, or null, if value is null and conversionType is not a value type.</returns> public static object ChangeType(object value, System.Type conversionType) { // have to use IsAssignableFrom() due to proxy classes if (value != null && !conversionType.IsAssignableFrom(value.GetType())) { if (IsNullableType(conversionType)) { System.Type arg = conversionType.GetGenericArguments()[0]; if (arg.IsEnum) { if (value is string) { value = Activator.CreateInstance(conversionType, Enum.Parse(arg, value as string)); } else { value = Activator.CreateInstance(conversionType, Enum.ToObject(arg, value)); } } else { value = Activator.CreateInstance(conversionType, Convert.ChangeType(value, arg)); } } else { if (conversionType.IsEnum) { if (value is string) { value = Enum.Parse(conversionType, value as string); } else { value = Enum.ToObject(conversionType, value); } } else { value = Convert.ChangeType(value, conversionType); } } } return(value); }
public override System.Threading.Tasks.Task WriteToStreamAsync(System.Type type, object value, System.IO.Stream writeStream, System.Net.Http.HttpContent content, System.Net.TransportContext transportContext) { var obj = new ExpandoObject() as IDictionary <string, Object>; if (type.IsSubclassOf(typeof(BaseMetaResponseModel)) && type.IsGenericType) { Type innerType = type.GetGenericArguments()[0]; var genericValue = (value as BaseMetaResponseModel); value = genericValue.Content; type = innerType; obj["meta"] = genericValue.Meta; } var root = GetRootFieldName(type, value); obj[root] = value; return(base.WriteToStreamAsync(type, obj as object, writeStream, content, transportContext)); }
private object ConvertToDictionary(object value, System.Type type, Dictionary <string, object> src) { Type typeDef = type.GetGenericTypeDefinition(); Type[] typeArgs = type.GetGenericArguments(); Type constructed = typeDef.MakeGenericType(typeArgs); object dict = Activator.CreateInstance(constructed); Dictionary <string, object> srcDict = (Dictionary <string, object>)value; foreach (KeyValuePair <string, object> entry in srcDict) { object elementKey = ConvertToType(entry.Key, typeArgs[0], src); object elementValue = ConvertToType(entry.Value, typeArgs[1], src); dict.GetType().GetMethod("Add").Invoke(dict, new[] { elementKey, elementValue }); } return(dict); }
protected override bool TryConvertMap(IReferenceMap referenceMap, TypeReference elementType, object value, out object result) { if (value == null) { result = null; return(true); } Type valueType = value.GetType(); Type dictionaryInterface = valueType.GetInterfaces() .FirstOrDefault(i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IDictionary <,>)); if (dictionaryInterface == null || !dictionaryInterface.GetGenericArguments()[0].IsAssignableFrom(typeof(string))) { result = null; return(false); } IEnumerable <string> keys = (IEnumerable <string>)valueType.GetProperty("Keys").GetValue(value); PropertyInfo indexer = ReflectionUtils.GetIndexer(valueType); JObject resultObject = new JObject(); foreach (string key in keys) { object element = indexer.GetValue(value, new object[] { key }); if (!TryConvert(elementType, referenceMap, element, out object convertedElement)) { result = null; return(false); } if (convertedElement != null && !(convertedElement is String) && !convertedElement.GetType().IsPrimitive) { convertedElement = JObject.FromObject(convertedElement); } resultObject.Add(new JProperty(key, convertedElement)); } result = resultObject; return(true); }
public object Cast(object value) { System.Type type = NetReflector.ToNative(_type); if (null == type) { return(null); } if (IsNullable) { type = type.GetGenericArguments()[0]; } return(type.IsEnum ? ConvertEnum(type, value) : Convert.ChangeType(value, type)); }
public static Type GetValueType(FieldInfo fieldInfo) { Type referenceType = GetReferenceType(fieldInfo); if (referenceType.IsArray) { referenceType = referenceType.GetElementType(); } else if (IsList(referenceType)) { referenceType = referenceType.GetGenericArguments()[0]; } FieldInfo constantValueField = referenceType.GetField(ConstantValueName, NonPublicBindingFlag); return(constantValueField.FieldType); }
private Object ReadGenericList(AbstractHessianInput abstractHessianInput) { Type[] args = m_type.GetGenericArguments(); Type itemType = args[0]; Type listType = typeof(System.Collections.Generic.List <>).MakeGenericType(itemType); object list = Activator.CreateInstance(listType); abstractHessianInput.AddRef(list); while (!abstractHessianInput.IsEnd()) { object item = abstractHessianInput.ReadObject(itemType); listType.InvokeMember("Add", BindingFlags.InvokeMethod, null, list, new object[] { item }); } abstractHessianInput.ReadEnd(); return(list); }
private object ConvertToList(object value, System.Type type, Dictionary <string, object> src) { Type typeDef = type.GetGenericTypeDefinition(); Type[] typeArgs = type.GetGenericArguments(); Type constructed = typeDef.MakeGenericType(typeArgs); object list = Activator.CreateInstance(constructed); List <object> elements = (List <object>)value; int index = 0; foreach (object elementValue in elements) { object o = ConvertToType(elementValue, typeArgs[0], src); list.GetType().GetMethod("Add").Invoke(list, new[] { o }); ++index; } return(list); }
// ==================================================================================================================== static private object SetMember_OnGeneric(IGetComponentAttribute pGetComponentAttribute, MonoBehaviour pTargetMono, object pMemberOwner, MemberInfo pMember, System.Type pTypeField) { object pComponent = null; System.Type pTypeField_Generic = pTypeField.GetGenericTypeDefinition(); Type[] arrArgumentsType = pTypeField.GetGenericArguments(); if (pTypeField_Generic == typeof(List <>)) { pComponent = SetMember_OnList(pGetComponentAttribute, pTargetMono, pMemberOwner, pMember, pTypeField, arrArgumentsType); } else if (pTypeField_Generic == typeof(Dictionary <,>)) { pComponent = SetMember_OnDictionary(pGetComponentAttribute, pTargetMono, pMemberOwner, pMember, pTypeField, arrArgumentsType[0], arrArgumentsType[1]); } return(pComponent); }
/// <summary> /// Gets the type of the IList element. /// </summary> /// <returns> /// The IList element type if the supplied type is assignable from IList, otherwise <c>null</c>. /// </returns> /// <param name="type">An IList type.</param> public static System.Type GetIListElementType(System.Type type) { if (typeof(IList).IsAssignableFrom(type)) { if (type.IsArray) { return(type.GetElementType()); } else { return(type.GetGenericArguments()[0]); } } else { return(null); } }
/// <summary> /// 判断传入的类型定义是否为数值类型,或者是可空的泛型数据类型 <see cref="System.Nullable<T>"/> 并且其第一个泛型参数类型是数值类型。 /// </summary> /// <param name="_this">被判断的类型定义。</param> /// <returns>如果传入的类型定义是数值类型,或者其是一个泛型数据类型 <see cref="System.Nullable<T>"/> 并且其第一个泛型参数类型是数值类型,则返回 true;否则返回 false。</returns> public static bool IsNumericWithNullable(this System.Type _this) { Check.NotNull(_this); if (IsNumeric(_this)) { return(true); } else if (_this.IsGenericType) { Type genericType = _this.GetGenericTypeDefinition(); if (genericType == typeof(Nullable <>)) { Type[] genericParameters = _this.GetGenericArguments(); return(genericParameters.Length == 1 && IsNumeric(genericParameters[0])); } } return(false); }
public static DataTable ToDataTable(this IEnumerable query) { try { DataTable dtReturn = new DataTable(); PropertyInfo[] columnProperties = null; foreach (var record in query) { // use reflection to get column names for the table, only first time, others will follow if (columnProperties == null) { columnProperties = record.GetType().GetProperties(); foreach (PropertyInfo propertyInfo in columnProperties) { // sort out the issue of nullable types System.Type columnType = propertyInfo.PropertyType; if ((columnType.IsGenericType) && (columnType.GetGenericTypeDefinition() == typeof(Nullable <>))) { columnType = columnType.GetGenericArguments()[0]; } // add a column to the table dtReturn.Columns.Add(new DataColumn(propertyInfo.Name, columnType)); } } DataRow dataRow = dtReturn.NewRow(); foreach (PropertyInfo propertyInfo in columnProperties) { dataRow[propertyInfo.Name] = propertyInfo.GetValue(record, null) == null ? DBNull.Value : propertyInfo.GetValue(record, null); } dtReturn.Rows.Add(dataRow); } return(dtReturn); } catch (Exception ex) { } return(new DataTable()); }
public static FieldInfo[] GetFields(this SerializedProperty _serializableProperty) { object _serObject = _serializableProperty.serializedObject.targetObject; string _propertyPath = _serializableProperty.propertyPath; int _arrayDataIndex = _propertyPath.IndexOf(".Array.data"); // Its an array element, for each element of array "propertyPath" has index information, need to remove it if (_arrayDataIndex != -1) { _propertyPath = _propertyPath.Substring(0, _arrayDataIndex); } // Path is split into components string[] _propertyPathComponents = _propertyPath.Split('.'); BindingFlags _bindingAttribute = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance; // We are interating though property path, to get typeof property int _componentCount = _propertyPathComponents.Length; System.Type _containerObjectType = _serObject.GetType(); for (int _iter = 0; _iter < _componentCount; _iter++) { // Each component of property path is a variable of parent object string _fieldName = _propertyPathComponents[_iter]; FieldInfo _targetField = _containerObjectType.GetField(_fieldName, _bindingAttribute); // As we go deeper, update container object type _containerObjectType = _targetField.FieldType; } // If its an array element, our parent is currently pointing at array rather than element as we chucked index information if (_containerObjectType.IsArray) { _containerObjectType = _containerObjectType.GetElementType(); } else if (_containerObjectType.IsGenericType && _containerObjectType.GetGenericTypeDefinition() == typeof(List <>)) { _containerObjectType = _containerObjectType.GetGenericArguments()[0]; } return(_containerObjectType.GetAllFields()); }