public ArrayDescriptor(ITypeDescriptorFactory factory, Type type, bool emitDefaultValues, IMemberNamingConvention namingConvention) : base(factory, type, emitDefaultValues, namingConvention) { if (!type.IsArray) throw new ArgumentException(@"Expecting array type", nameof(type)); if (type.GetArrayRank() != 1) { throw new ArgumentException("Cannot support dimension [{0}] for type [{1}]. Only supporting dimension of 1".ToFormat(type.GetArrayRank(), type.FullName)); } ElementType = type.GetElementType(); }
/// <summary> /// Initializes a new instance of the <see cref="ObjectDescriptor" /> class. /// </summary> /// <param name="attributeRegistry">The attribute registry.</param> /// <param name="type">The type.</param> /// <exception cref="System.ArgumentException">Expecting arrat type;type</exception> public ArrayDescriptor(IAttributeRegistry attributeRegistry, Type type) : base(attributeRegistry, type, false) { if (!type.IsArray) throw new ArgumentException("Expecting array type", "type"); if (type.GetArrayRank() != 1) { throw new ArgumentException("Cannot support dimension [{0}] for type [{1}]. Only supporting dimension of 1".DoFormat(type.GetArrayRank(), type.FullName)); } elementType = type.GetElementType(); listType = typeof(List<>).MakeGenericType(ElementType); toArrayMethod = listType.GetMethod("ToArray"); }
/// <summary> /// Initializes a new instance of the <see cref="ObjectDescriptor" /> class. /// </summary> /// <param name="factory">The factory.</param> /// <param name="type">The type.</param> /// <exception cref="System.ArgumentException">Expecting arrat type;type</exception> public ArrayDescriptor(ITypeDescriptorFactory factory, Type type) : base(factory, type) { if (!type.IsArray) throw new ArgumentException("Expecting array type", "type"); if (type.GetArrayRank() != 1) { throw new ArgumentException("Cannot support dimension [{0}] for type [{1}]. Only supporting dimension of 1".ToFormat(type.GetArrayRank(), type.FullName)); } Category = DescriptorCategory.Array; elementType = type.GetElementType(); listType = typeof(List<>).MakeGenericType(ElementType); toArrayMethod = listType.GetMethod("ToArray"); }
public ArrayDecorator(IProtoSerializer tail, int fieldNumber, bool writePacked, WireType packedWireType, Type arrayType, bool overwriteList, bool supportNull) : base(tail) { Helpers.DebugAssert(arrayType != null, "arrayType should be non-null"); Helpers.DebugAssert(arrayType.IsArray && arrayType.GetArrayRank() == 1, "should be single-dimension array; " + arrayType.FullName); this.itemType = arrayType.GetElementType(); #if NO_GENERICS Type underlyingItemType = itemType; #else Type underlyingItemType = supportNull ? itemType : (Nullable.GetUnderlyingType(itemType) ?? itemType); #endif Helpers.DebugAssert(underlyingItemType == Tail.ExpectedType, "invalid tail"); Helpers.DebugAssert(Tail.ExpectedType != typeof(byte), "Should have used BlobSerializer"); if ((writePacked || packedWireType != WireType.None) && fieldNumber <= 0) throw new ArgumentOutOfRangeException("fieldNumber"); if (!ListDecorator.CanPack(packedWireType)) { if (writePacked) throw new InvalidOperationException("Only simple data-types can use packed encoding"); packedWireType = WireType.None; } this.fieldNumber = fieldNumber; this.packedWireType = packedWireType; if (writePacked) options |= OPTIONS_WritePacked; if (overwriteList) options |= OPTIONS_OverwriteList; if (supportNull) options |= OPTIONS_SupportNull; this.arrayType = arrayType; }
/// <summary> /// Reads the JSON representation of the object. /// </summary> /// <param name="reader">The <see cref="T:Newtonsoft.Json.JsonReader"/> to read from.</param> /// <param name="objectType">Type of the object.</param> /// <param name="existingValue">The existing value of object being read.</param> /// <param name="serializer">The calling serializer.</param> /// <returns>The object value.</returns> public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { // Handle null values if (reader.TokenType == JsonToken.Null) return null; var arrayItemType = objectType.GetElementType(); var arrayRank = objectType.GetArrayRank(); // Retrieve all the values from the Json var arrayValues = ReadRank(reader, serializer); // Determine the lengths of all ranks for the array var rankLengthList = GetRankLengthList(arrayValues); // If empty values were found, make sure the ranks match in size for (var i = rankLengthList.Count; i < arrayRank; i++) { rankLengthList.Add(0); } var rankLengthArray = rankLengthList.ToArray(); // Create the array that will hold the values var retVal = Array.CreateInstance(arrayItemType, rankLengthArray); // Make the assignments SetValues(retVal, rankLengthArray, new int[0], 0, arrayValues); return retVal; }
public FormalTypeName(Type type) { if (type.IsArray) { _arrayRank = type.GetArrayRank(); _arrayElementType = new FormalTypeName(type.GetElementType()); } _isGenericTypeArg = type.IsGenericParameter; _isRef = !type.IsValueType; _isByRef = type.IsByRef; _name = type.Name; if (_isByRef && _name.EndsWith("&")) _name = _name.Remove(_name.Length - 1); _namespace = type.Namespace; if (type.IsNested && type.FullName != null) { _wrapperClass = new FormalTypeName(type.DeclaringType); } if (type.IsGenericType) { if (type.IsGenericTypeDefinition) { ReadGenericDefinition(type); } else { ReadGenericDefinition(type.GetGenericTypeDefinition()); var args = type.GetGenericArguments(); _genericInstance = new FormalTypeName[args.Length]; for (var i = 0; i < args.Length; i++) _genericInstance[i] = new FormalTypeName(args[i]); } } }
internal static Type AddElementTypes(SerializationInfo info, Type type) { List<int> list = new List<int>(); while (type.HasElementType) { if (type.IsSzArray) { list.Add(3); } else if (type.IsArray) { list.Add(type.GetArrayRank()); list.Add(2); } else if (type.IsPointer) { list.Add(1); } else if (type.IsByRef) { list.Add(4); } type = type.GetElementType(); } info.AddValue("ElementTypes", list.ToArray(), typeof(int[])); return type; }
public static bool IsListType(this System.Type tp, bool ignoreAsInterface) { if (tp == null) { return(false); } if (tp.IsArray) { return(tp.GetArrayRank() == 1); } if (ignoreAsInterface) { //if (tp == typeof(System.Collections.ArrayList) || (tp.IsGenericType && tp.GetGenericTypeDefinition() == typeof(List<>))) return true; if (tp.IsGenericType && tp.GetGenericTypeDefinition() == typeof(List <>)) { return(true); } } else { var interfaces = tp.GetInterfaces(); //if (interfaces.Contains(typeof(System.Collections.IList)) || interfaces.Contains(typeof(IList<>))) if (Array.IndexOf(interfaces, typeof(System.Collections.IList)) >= 0 || Array.IndexOf(interfaces, typeof(IList <>)) >= 0) { return(true); } } return(false); }
private static StringBuilder AppendPrettyNameCore(this StringBuilder name, Type type, PrettyNameContext context) { // Suffixes (array, ref, pointer) if (type.IsArray) return name .AppendPrettyName(type.GetElementType(), context) .Append('[') .Append(',', type.GetArrayRank() - 1) .Append(']'); else if (type.IsByRef) return name .AppendPrettyName(type.GetElementType(), context) .Append('&'); else if (type.IsPointer) return name .AppendPrettyName(type.GetElementType(), context) .Append('*'); // Prefixes (nesting, namespace) if (type.IsNested) name.AppendPrettyNameCore(type.DeclaringType, context) .Append('.'); else if (context.IsQualified) name.Append(type.Namespace) .Append('.'); // Name and arguments if (type.IsGenericType) return name .Append(type.Name.WithoutGenericSuffix()) .AppendPrettyArguments(type, context); else return name .Append(type.Name); }
internal static WriteJsonValue GetWriteJsonMethod(Type type) { var t = Reflection.GetJsonDataType (type); if (t == JsonDataType.Primitive) { return typeof (decimal).Equals (type) ? WriteDecimal : typeof (byte).Equals (type) ? WriteByte : typeof (sbyte).Equals (type) ? WriteSByte : typeof (short).Equals (type) ? WriteInt16 : typeof (ushort).Equals (type) ? WriteUInt16 : typeof (uint).Equals (type) ? WriteUInt32 : typeof (ulong).Equals (type) ? WriteUInt64 : typeof (char).Equals (type) ? WriteChar : (WriteJsonValue)WriteUnknown; } else if (t == JsonDataType.Undefined) { return type.IsSubclassOf (typeof (Array)) && type.GetArrayRank () > 1 ? WriteMultiDimensionalArray : type.IsSubclassOf (typeof (Array)) && typeof (byte[]).Equals (type) == false ? WriteArray : typeof (KeyValuePair<string,object>).Equals (type) ? WriteKeyObjectPair : typeof (KeyValuePair<string,string>).Equals (type) ? WriteKeyValuePair : (WriteJsonValue)WriteObject; } else { return _convertMethods[(int)t]; } }
internal static Type AddElementTypes(SerializationInfo info, Type type) { List<int> elementTypes = new List<int>(); while(type.HasElementType) { if (type.IsSzArray) { elementTypes.Add(SzArray); } else if (type.IsArray) { elementTypes.Add(type.GetArrayRank()); elementTypes.Add(Array); } else if (type.IsPointer) { elementTypes.Add(Pointer); } else if (type.IsByRef) { elementTypes.Add(ByRef); } type = type.GetElementType(); } info.AddValue("ElementTypes", elementTypes.ToArray(), typeof(int[])); return type; }
static string ArrayTypeName(Type type) { if (!type.IsArray) return null; string basename = Get(type.GetElementType()); string rankCommas = new string(',', type.GetArrayRank() - 1); return basename + "[" + rankCommas + "]"; }
// // From a one-dimensional array-type S[] to System.Collections.IList<T> and base // interfaces of this interface, provided there is an implicit reference conversion // from S to T. // static bool Array_To_IList (Type array, Type list, bool isExplicit) { if ((array.GetArrayRank () != 1) || !TypeManager.IsGenericType (list)) return false; Type gt = TypeManager.DropGenericTypeArguments (list); if ((gt != TypeManager.generic_ilist_type) && (gt != TypeManager.generic_icollection_type) && (gt != TypeManager.generic_ienumerable_type)) return false; Type element_type = TypeManager.GetElementType (array); Type arg_type = TypeManager.TypeToCoreType (TypeManager.GetTypeArguments (list) [0]); if (element_type == arg_type) return true; if (isExplicit) return ExplicitReferenceConversionExists (element_type, arg_type); Type t = TypeManager.GetElementType (array); if (MyEmptyExpr == null) MyEmptyExpr = new EmptyExpression (t); else MyEmptyExpr.SetType (t); return ImplicitReferenceConversionExists (MyEmptyExpr, arg_type); }
/// <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 Aggregate(Type expectedType, Type actualType) { Type actualElementType = actualType.GetSequenceElementType(); if (!expectedType.IsAssignableFrom(actualType)) { Type expectedElementType = expectedType.GetSequenceElementType(); 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.GetGenericTypeDefinition() == typeof(IQueryable<>)) body = Expression.Call(typeof(Queryable), "AsQueryable", new Type[] { expectedElementType }, CoerceElement(expectedElementType, p)); else if (expectedType.IsArray && expectedType.GetArrayRank() == 1) body = Expression.Call(typeof(Enumerable), "ToArray", new Type[] { expectedElementType }, CoerceElement(expectedElementType, p)); else if (expectedType.IsAssignableFrom(typeof(List<>).MakeGenericType(actualElementType))) body = Expression.Call(typeof(Enumerable), "ToList", new Type[] { expectedElementType }, CoerceElement(expectedElementType, p)); else { 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; }
TypeDef CreateSpecialTypeDefOrNull(Type type) { BuiltInTypeDef typeDef = null; if (typeof(IEnumerable).IsAssignableFrom(type)) { if (type.IsArray && type.GetArrayRank() == 1) { var elementType = type.GetElementType(); var typeDefOfContainedType = GetOrCreateTypeDef(new QualifiedClassName(elementType), elementType); typeDef = new BuiltInTypeDef(type, "", string.Format("{0}[]", typeDefOfContainedType.FullyQualifiedTsTypeName)); } else if (!type.IsGenericType) { typeDef = new BuiltInTypeDef(type, "", "any[]"); } else if (type.IsGenericType && type.GetGenericArguments().Length == 1) { var elementType = type.GetGenericArguments()[0]; var typeDefOfContainedType = GetOrCreateTypeDef(new QualifiedClassName(elementType), elementType); typeDef = new BuiltInTypeDef(type, "", string.Format("{0}[]", typeDefOfContainedType.FullyQualifiedTsTypeName)); } } if (typeDef != null) { _types.Add(type, typeDef); } return typeDef; }
void SetArrayDimensions(Type type) { if (type.IsArray && type != typeof(Array)) { SetArrayDimensions(type.GetElementType()); arrays.Insert(0, type.GetArrayRank()); } }
/// <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; }
static string generateArrayString(Type type) { var rankString = string.Empty; for (int i = 0; i < type.GetArrayRank() - 1; i++) { rankString += ","; } return Generate(type.GetElementType()) + "[" + rankString + "]"; }
private Type ImportImpl(System.Type type) { if (type.Assembly == typeof(IKVM.Reflection.Type).Assembly) { throw new ArgumentException("Did you really want to import " + type.FullName + "?"); } if (type.HasElementType) { if (type.IsArray) { if (type.Name.EndsWith("[]")) { return(Import(type.GetElementType()).MakeArrayType()); } else { return(Import(type.GetElementType()).MakeArrayType(type.GetArrayRank())); } } else if (type.IsByRef) { return(Import(type.GetElementType()).MakeByRefType()); } else if (type.IsPointer) { return(Import(type.GetElementType()).MakePointerType()); } else { throw new InvalidOperationException(); } } else if (type.IsGenericParameter) { if (type.DeclaringMethod != null) { throw new NotImplementedException(); } else { return(Import(type.DeclaringType).GetGenericArguments()[type.GenericParameterPosition]); } } else if (type.IsGenericType && !type.IsGenericTypeDefinition) { System.Type[] args = type.GetGenericArguments(); Type[] importedArgs = new Type[args.Length]; for (int i = 0; i < args.Length; i++) { importedArgs[i] = Import(args[i]); } return(Import(type.GetGenericTypeDefinition()).MakeGenericType(importedArgs)); } else { return(Import(type.Assembly).GetType(type.FullName)); } }
/// <inheritdoc /> public ConversionCost GetConversionCost(Type sourceType, Type targetType, IConverter elementConverter) { if (sourceType.IsArray && targetType.IsArray && sourceType.GetArrayRank() == 1 && targetType.GetArrayRank() == 1) return elementConverter.GetConversionCost(sourceType.GetElementType(), targetType.GetElementType()) .Add(ConversionCost.Typical); return ConversionCost.Invalid; }
static IReturnType Create(IProjectContent pc, IEntity member, Type type, bool createLazyReturnType, bool forceGenericType) { if (type.IsByRef) { // TODO: Use ByRefRefReturnType return Create(pc, member, type.GetElementType(), createLazyReturnType); } else if (type.IsPointer) { return new PointerReturnType(Create(pc, member, type.GetElementType(), createLazyReturnType)); } else if (type.IsArray) { return new ArrayReturnType(pc, Create(pc, member, type.GetElementType(), createLazyReturnType), type.GetArrayRank()); } else if (type.IsGenericType && (forceGenericType || !type.IsGenericTypeDefinition)) { Type[] args = type.GetGenericArguments(); List<IReturnType> para = new List<IReturnType>(args.Length); for (int i = 0; i < args.Length; ++i) { para.Add(Create(pc, member, args[i], createLazyReturnType)); } return new ConstructedReturnType(Create(pc, member, type.GetGenericTypeDefinition(), createLazyReturnType, false), para); } else if (type.IsGenericParameter) { IClass c = (member is IClass) ? (IClass)member : (member is IMember) ? ((IMember)member).DeclaringType : null; if (c != null && type.GenericParameterPosition < c.TypeParameters.Count) { if (c.TypeParameters[type.GenericParameterPosition].Name == type.Name) { return new GenericReturnType(c.TypeParameters[type.GenericParameterPosition]); } } if (type.DeclaringMethod != null) { IMethod method = member as IMethod; if (method != null) { if (type.GenericParameterPosition < method.TypeParameters.Count) { return new GenericReturnType(method.TypeParameters[type.GenericParameterPosition]); } return new GenericReturnType(new DefaultTypeParameter(method, type)); } } return new GenericReturnType(new DefaultTypeParameter(c, type)); } else { string name = type.FullName; if (name == null) throw new ApplicationException("type.FullName returned null. Type: " + type.ToString()); int typeParameterCount = 0; if (name.Length > 2) { if (name[name.Length - 2] == '`') { typeParameterCount = int.Parse(name[name.Length - 1].ToString()); name = name.Substring(0, name.Length - 2); } } if (name.IndexOf('+') > 0) { name = name.Replace('+', '.'); } if (!createLazyReturnType) { IClass c = pc.GetClass(name, typeParameterCount); if (c != null) return c.DefaultReturnType; // example where name is not found: pointers like System.Char* // or when the class is in a assembly that is not referenced } return new GetClassReturnType(pc, name, typeParameterCount); } }
public override bool MatchesType(Type t) { Guard.ArgumentNotNull(t, "t"); if (!t.IsArray || t.GetArrayRank() != 1) return false; Type elementType = t.GetElementType(); return elementType.IsGenericParameter && elementType.Name == genericParameterName; }
public bool Handles(Type type) { if (!type.IsArray) return false; if (type.GetArrayRank() != 1) throw new NotSupportedException(String.Format("Multi-dim arrays not supported: {0}", type.FullName)); return true; }
// JSON.NET cannot, when reading, use PreserveReferencesHandling on arrays, although it fully supports it on writing. // Doing so while being able to fully preserve circular references would require storing the length of the array, // or reading ahead in the JSON to compute the length. For arrays that could contain reference types, we choose the latter. // For arrays of primitive types, there is no issue. // TODO: on serialization, the type of the object is available, but is the expected type (ie, the one that we'll be fed during deserialization) available? // need this to at least detect covariance cases... public override bool CanConvert(Type objectType) { if (!typeof(Array).IsAssignableFrom(objectType)) return false; if (objectType.GetArrayRank() > 1) throw new NotImplementedException(); return true; }
internal TypeNode GetTypeNodeFor(AssemblyNode assembly, Type t) { if (t.IsArray) { int rank = t.GetArrayRank(); Type et = t.GetElementType(); TypeNode type = assembly.GetType(Identifier.For(et.Namespace), Identifier.For(et.Name)); return type.GetArrayType(rank); } else { return assembly.GetType(Identifier.For(t.Namespace), Identifier.For(t.Name)); } }
static void AppendTypeName(StringBuilder b, Type type) { if (type == null) { return; } if (type.IsGenericType) { AppendTypeNameWithArguments(b, type.GetElementType(), type.GetGenericArguments()); } else if (type.HasElementType) { AppendTypeName(b, type.GetElementType()); if (type.IsArray) { b.Append('['); if (type.GetArrayRank() > 1) { for (int i = 0; i < type.GetArrayRank(); i++) { if (i > 0) b.Append(','); b.Append("0:"); } } b.Append(']'); } if (type.IsByRef) { b.Append('@'); } if (type.IsPointer) { b.Append('*'); } } else { if (type.IsGenericParameter) { b.Append('`'); if (type.DeclaringMethod != null) { b.Append('`'); } b.Append(type.GenericParameterPosition); } else if (type.DeclaringType != null) { AppendTypeName(b, type.DeclaringType); b.Append('.'); b.Append(type.Name); } else { b.Append(type.FullName); } } }
// Create an array node given an existing CLR array type public ArrayTypeSig(System.Type tArray, ISemanticResolver s) { Debug.Assert(tArray != null); m_filerange = null; m_cDimension = tArray.GetArrayRank(); Debug.Assert(m_cDimension == 1, "@todo - only 1d arrays currently implemented"); m_ArrayTypeRec = s.ResolveCLRTypeToBlueType(tArray).AsArrayType; m_sigBase = null; // left as null. }
/// <include file='doc\CodeTypeReference.uex' path='docs/doc[@for="CodeTypeReference.CodeTypeReference"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public CodeTypeReference(Type type) { if (type.IsArray) { this.arrayRank = type.GetArrayRank(); this.arrayElementType = new CodeTypeReference(type.GetElementType()); this.baseType = null; } else { this.arrayRank = 0; this.arrayElementType = null; this.baseType = type.FullName; } }
public ITypeImporter Bind(ImportContext context, Type type) { if (context == null) throw new ArgumentNullException("context"); if (type == null) throw new ArgumentNullException("type"); return type.IsArray && type.GetArrayRank() == 1 ? new ArrayImporter(type) : null; }
public object GetArray(PropertyInfo propertyInfo, Type type) { StandardArrayRandomizer.Logger.Debug($"Entering GetArray. propertyInfo: {propertyInfo.GetExtendedMemberInfoString()}, type: {type}"); Array resultArray; int rank = type.GetArrayRank(); Type basicType = type.GetElementType(); if (rank > 1) { StandardArrayRandomizer.Logger.Debug($"rank > 1: {rank}"); var dimensionSizes = new int[rank]; for (int i = 0; i < dimensionSizes.Length; i++) { StandardArrayRandomizer.Logger.Debug($"dimensionSize {i}: {dimensionSizes[i]}"); dimensionSizes[i] = this.random.Next(StandardArrayRandomizer.MaxDimensionLength) + 1; } EmptyArrayResult emptyArrayResult = StandardArrayRandomizer.GetEmptyArray(type, dimensionSizes); do { object resultElement = this.valueGenerator.GetValue(propertyInfo, basicType); StandardArrayRandomizer.Logger.Debug($"Result element: {resultElement}"); emptyArrayResult.Array.SetValue(resultElement, emptyArrayResult.Indices.Value); emptyArrayResult.Indices++; } while (!emptyArrayResult.Indices.Overflow); resultArray = emptyArrayResult.Array; } else { StandardArrayRandomizer.Logger.Debug($"rank <= 1: {rank}"); int dimensionLength = this.random.Next(StandardArrayRandomizer.MaxDimensionLength) + 1; ConstructorInfo constructor = type.GetConstructor(new[] { typeof(int) }); resultArray = (Array)constructor.Invoke(new object[] { dimensionLength }); for (int i = 0; i < dimensionLength; i++) { object value = this.valueGenerator.GetValue(propertyInfo, basicType); StandardArrayRandomizer.Logger.Debug($"Element value: {value}"); resultArray.SetValue(value, i); } } StandardArrayRandomizer.Logger.Debug("Exiting GetArray"); return resultArray; }
public static bool IsListType(this System.Type tp, bool ignoreAsInterface, out System.Type innerType) { innerType = null; if (tp == null) { return(false); } if (tp.IsArray) { if (tp.GetArrayRank() == 1) { innerType = tp.GetElementType(); return(true); } else { return(false); } } if (ignoreAsInterface) { if (tp.IsGenericType && tp.GetGenericTypeDefinition() == typeof(List <>)) { innerType = tp.GetGenericArguments()[0]; return(true); } else { return(false); } } else { var interfaces = tp.GetInterfaces(); if (Array.IndexOf(interfaces, typeof(System.Collections.IList)) >= 0 || Array.IndexOf(interfaces, typeof(IList <>)) >= 0) { if (tp.IsGenericType) { innerType = tp.GetGenericArguments()[0]; } else { innerType = typeof(object); } return(true); } } return(false); }
public ArrayImporter(Type arrayType) { if (arrayType == null) arrayType = typeof(object[]); if (!arrayType.IsArray) throw new ArgumentException(string.Format("{0} is not an array.", arrayType.FullName), "arrayType"); if (arrayType.GetArrayRank() != 1) throw new ArgumentException(string.Format("{0} is not one-dimension array. Multi-dimensional arrays are not supported.", arrayType.FullName), "arrayType"); _arrayType = arrayType; }
private static Type AssertArrayType(Type type) { if (type == null) return typeof(object[]); if (!type.IsArray) throw new ArgumentException(string.Format("{0} is not an array.", type.FullName), "arrayType"); if (type.GetArrayRank() != 1) throw new ArgumentException(string.Format("{0} is not one-dimension array. Multi-dimensional arrays are not supported.", type.FullName), "arrayType"); return type; }
internal static string Type(System.Type type, bool dropNamespaces = false) { string assemblyQualifiedName; Exception exception; if (type == null) { return(string.Empty); } if (type.IsGenericType && !type.IsGenericTypeDefinition) { string str2 = Type(type.GetGenericTypeDefinition(), dropNamespaces); int num = str2.LastIndexOf('`'); int length = str2.Length - (str2.Length - num); StringBuilder builder = new StringBuilder(str2, 0, length, 0x200); builder.Append('['); bool flag = true; foreach (System.Type type2 in type.GetGenericArguments()) { if (!flag) { builder.Append(','); } flag = false; builder.Append(Type(type2, dropNamespaces)); } builder.Append(']'); assemblyQualifiedName = builder.ToString(); } else if (type.IsArray) { string str3 = Type(type.GetElementType(), dropNamespaces); StringBuilder builder2 = new StringBuilder(str3, str3.Length + 10); builder2.Append("["); for (int i = 0; i < (type.GetArrayRank() - 1); i++) { builder2.Append(","); } builder2.Append("]"); assemblyQualifiedName = builder2.ToString(); } else { assemblyQualifiedName = TypeAccelerators.FindBuiltinAccelerator(type) ?? (dropNamespaces ? type.Name : type.ToString()); } if ((!type.IsGenericParameter && !type.ContainsGenericParameters) && (!dropNamespaces && (LanguagePrimitives.ConvertStringToType(assemblyQualifiedName, out exception) != type))) { assemblyQualifiedName = type.AssemblyQualifiedName; } return(assemblyQualifiedName); }
Symbol GetSymbol(System.Type type) { NameSpace ns = GetNameSpace(type); string name = GetName(type); Type t = ns.members[name] as Type; if (t != null) { return(t); } if (type.IsInterface) { t = GetInterface(type, ns.members); } else if (type.IsEnum) { t = GetEnum(type, ns.members); } else if (type.IsValueType) { t = GetStruct(type, ns.members); } else if (type.IsClass && (type.BaseType == typeof(System.Delegate) || type.BaseType == typeof(System.MulticastDelegate))) { t = GetDelegate(type, ns.members); } else if (type.IsArray) { t = new ArrayType(GetType(type.GetElementType()), type.GetArrayRank(), global.Types.Array); } else if (type.IsByRef) { t = new ManagedPointerType(GetType(type.GetElementType())); } else if (type.IsPointer) { t = new UnmanagedPointerType(GetType(type.GetElementType())); } else if (type.IsClass || type.IsAnsiClass) { t = GetClass(type, ns.members); } else { Debug.Fail("unknown type " + type.FullName); } t.module = type.Assembly.Location.ToLower(); t.type = type; return(t); }
internal static string Type(System.Type type) { if (type == null) { return(string.Empty); } string typeName; if (type.IsGenericType && !type.IsGenericTypeDefinition) { string str = ToStringCodeMethods.Type(type.GetGenericTypeDefinition()); int num = str.LastIndexOf('`'); int length = str.Length - (str.Length - num); StringBuilder stringBuilder = new StringBuilder(str, 0, length, 512); stringBuilder.Append('['); bool flag = true; foreach (System.Type genericArgument in type.GetGenericArguments()) { if (!flag) { stringBuilder.Append(','); } flag = false; stringBuilder.Append(ToStringCodeMethods.Type(genericArgument)); } stringBuilder.Append(']'); typeName = stringBuilder.ToString(); } else if (type.IsArray) { string str = ToStringCodeMethods.Type(type.GetElementType()); StringBuilder stringBuilder = new StringBuilder(str, str.Length + 10); stringBuilder.Append("["); for (int index = 0; index < type.GetArrayRank() - 1; ++index) { stringBuilder.Append(","); } stringBuilder.Append("]"); typeName = stringBuilder.ToString(); } else { typeName = TypeAccelerators.FindBuiltinAccelerator(type) ?? type.ToString(); } if (!type.IsGenericParameter && !type.ContainsGenericParameters && LanguagePrimitives.ConvertStringToType(typeName, out Exception _) != type) { typeName = type.AssemblyQualifiedName; } return(typeName); }
/// <inheritdoc/> public override IBsonSerializer GetSerializer(Type type, IBsonSerializerRegistry serializerRegistry) { if (type == null) { throw new ArgumentNullException("type"); } var typeInfo = type.GetTypeInfo(); if (typeInfo.IsGenericType && typeInfo.ContainsGenericParameters) { var message = string.Format("Generic type {0} has unassigned type parameters.", BsonUtils.GetFriendlyTypeName(type)); throw new ArgumentException(message, "type"); } Type serializerType; if (__serializerTypes.TryGetValue(type, out serializerType)) { return CreateSerializer(serializerType, serializerRegistry); } if (typeInfo.IsGenericType && !typeInfo.ContainsGenericParameters) { Type serializerTypeDefinition; if (__serializerTypes.TryGetValue(type.GetGenericTypeDefinition(), out serializerTypeDefinition)) { return CreateGenericSerializer(serializerTypeDefinition, type.GetGenericArguments(), serializerRegistry); } } if (type.IsArray) { var elementType = type.GetElementType(); switch (type.GetArrayRank()) { case 1: var arraySerializerDefinition = typeof(ArraySerializer<>); return CreateGenericSerializer(arraySerializerDefinition, new[] { elementType }, serializerRegistry); case 2: var twoDimensionalArraySerializerDefinition = typeof(TwoDimensionalArraySerializer<>); return CreateGenericSerializer(twoDimensionalArraySerializerDefinition, new[] { elementType }, serializerRegistry); case 3: var threeDimensionalArraySerializerDefinition = typeof(ThreeDimensionalArraySerializer<>); return CreateGenericSerializer(threeDimensionalArraySerializerDefinition, new[] { elementType }, serializerRegistry); default: var message = string.Format("No serializer found for array for rank {0}.", type.GetArrayRank()); throw new BsonSerializationException(message); } } return GetCollectionSerializer(type, serializerRegistry); }
internal static bool TypesEqual(CodeTypeReference typeLeft, System.Type typeRight) { if (typeRight.IsArray && (typeLeft.ArrayRank != typeRight.GetArrayRank())) { return(false); } if (!typeLeft.BaseType.Equals(typeRight.FullName)) { return(false); } if (typeLeft.ArrayRank > 0) { return(TypesEqual(typeLeft.ArrayElementType, typeRight.GetElementType())); } return(true); }
public static bool IsListType(System.Type tp) { if (tp == null) { return(false); } if (tp.IsArray) { return(tp.GetArrayRank() == 1); } var interfaces = tp.GetInterfaces(); if (Array.IndexOf(interfaces, typeof(System.Collections.IList)) >= 0 || Array.IndexOf(interfaces, typeof(IList <>)) >= 0) { return(true); } return(false); }
public static bool IsListType(this System.Type tp) { if (tp == null) { return(false); } if (tp.IsArray) { return(tp.GetArrayRank() == 1); } var interfaces = tp.GetInterfaces(); if (interfaces.Contains(typeof(System.Collections.IList)) || interfaces.Contains(typeof(IList <>))) { return(true); } return(false); }
private static bool IsTypeSupported(MessagePartDescription bodyDescription) { System.Type type = bodyDescription.Type; if (type == null) { throw System.ServiceModel.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(System.ServiceModel.SR.GetString("SFxMessagePartDescriptionMissingType", new object[] { bodyDescription.Name, bodyDescription.Namespace }))); } if (!bodyDescription.Multiple) { if (type == typeof(void)) { return(true); } if (type.IsEnum) { return(false); } switch (System.Type.GetTypeCode(type)) { case TypeCode.Object: if ((!type.IsArray || (type.GetArrayRank() != 1)) || !IsArrayTypeSupported(type.GetElementType())) { break; } return(true); case TypeCode.Boolean: case TypeCode.Int32: case TypeCode.Int64: case TypeCode.Single: case TypeCode.Double: case TypeCode.Decimal: case TypeCode.DateTime: case TypeCode.String: return(true); } } return(false); }
private static bool IsFieldType(TypeInfo typeInfo, bool canBeArray = true) { bool IsValidArray() { if (!typeInfo.IsArray) { return(false); } if (typeInfo.GetArrayRank() != 1) { return(false); } var arrayType = typeInfo.GetElementType().GetTypeInfo(); return(IsFieldType(arrayType, false)); } return(typeof(IRdBindable).GetTypeInfo().IsAssignableFrom(typeInfo) || IsPrimitive(typeInfo.AsType()) || typeInfo.IsEnum || canBeArray && IsValidArray() || IsNullable(typeInfo, type => IsPrimitive(type) || type.GetTypeInfo().IsEnum)); }
public static string GetSignature(object obj) { if (obj == null) { return("Ljava/lang/Object;"); } System.Type type = !(obj is System.Type) ? obj.GetType() : (System.Type)obj; if (AndroidReflection.IsPrimitive(type)) { if (type.Equals(typeof(int))) { return("I"); } if (type.Equals(typeof(bool))) { return("Z"); } if (type.Equals(typeof(byte))) { return("B"); } if (type.Equals(typeof(short))) { return("S"); } if (type.Equals(typeof(long))) { return("J"); } if (type.Equals(typeof(float))) { return("F"); } if (type.Equals(typeof(double))) { return("D"); } if (type.Equals(typeof(char))) { return("C"); } return(string.Empty); } if (type.Equals(typeof(string))) { return("Ljava/lang/String;"); } if (obj is AndroidJavaProxy) { return("L" + new AndroidJavaObject(((AndroidJavaProxy)obj).javaInterface.GetRawClass()).Call <string>("getName") + ";"); } if (type.Equals(typeof(AndroidJavaRunnable))) { return("Ljava/lang/Runnable;"); } if (type.Equals(typeof(AndroidJavaClass))) { return("Ljava/lang/Class;"); } if (type.Equals(typeof(AndroidJavaObject))) { if (obj == type) { return("Ljava/lang/Object;"); } using (AndroidJavaObject androidJavaObject = ((AndroidJavaObject)obj).Call <AndroidJavaObject>("getClass")) return("L" + androidJavaObject.Call <string>("getName") + ";"); } else { if (AndroidReflection.IsAssignableFrom(typeof(Array), type)) { if (type.GetArrayRank() != 1) { throw new Exception("JNI: System.Array in n dimensions is not allowed"); } StringBuilder stringBuilder = new StringBuilder(); stringBuilder.Append('['); stringBuilder.Append(_AndroidJNIHelper.GetSignature((object)type.GetElementType())); return(stringBuilder.ToString()); } throw new Exception("JNI: Unknown signature for type '" + (object)type + "' (obj = " + obj + ") " + (type != obj ? "instance" : "equal")); } }
private Type ImportImpl(System.Type type) { if (type.Assembly == typeof(IKVM.Reflection.Type).Assembly) { throw new ArgumentException("Did you really want to import " + type.FullName + "?"); } if (type.HasElementType) { if (type.IsArray) { if (type.Name.EndsWith("[]")) { return(Import(type.GetElementType()).MakeArrayType()); } else { return(Import(type.GetElementType()).MakeArrayType(type.GetArrayRank())); } } else if (type.IsByRef) { return(Import(type.GetElementType()).MakeByRefType()); } else if (type.IsPointer) { return(Import(type.GetElementType()).MakePointerType()); } else { throw new InvalidOperationException(); } } else if (type.IsGenericParameter) { if (type.DeclaringMethod != null) { throw new NotImplementedException(); } else { return(Import(type.DeclaringType).GetGenericArguments()[type.GenericParameterPosition]); } } else if (type.IsGenericType && !type.IsGenericTypeDefinition) { System.Type[] args = type.GetGenericArguments(); Type[] importedArgs = new Type[args.Length]; for (int i = 0; i < args.Length; i++) { importedArgs[i] = Import(args[i]); } return(Import(type.GetGenericTypeDefinition()).MakeGenericType(importedArgs)); } else if (type.Assembly == typeof(object).Assembly) { // make sure mscorlib types always end up in our mscorlib return(ResolveType(Mscorlib, type.FullName)); } else { // FXBUG we parse the FullName here, because type.Namespace and type.Name are both broken on the CLR return(ResolveType(Import(type.Assembly), type.FullName)); } }
// // Generate the "Signature2" binary serialization string for Type objects appearing inside serialized MethodBase and PropertyInfo signatures. // // Because the string is effectively a file format for serialized Reflection objects, it must be exactly correct. If missing // metadata prevents generating the string, this method throws a MissingMetadata exception. // // "withinGenericArgument" is used to track whether we're in the middle of serializing a generic type argument. // Some of the string-generation rules change when in that state: // // - Generic type parameters no longer get prepended with "!" or "!!". // - Plain old types are serialized as assembly-qualified names enclosed in square brackets. // private static void AppendSerializationString(this StringBuilder sb, Type type, bool withinGenericTypeArgument = false) { if (type.HasElementType) { sb.AppendSerializationString(type.GetElementType(), withinGenericTypeArgument); if (type.IsSZArray) { sb.Append("[]"); } else if (type.IsVariableBoundArray) { sb.Append('['); int rank = type.GetArrayRank(); if (rank == 1) { sb.Append('*'); } else { sb.Append(',', rank - 1); } sb.Append(']'); } else if (type.IsByRef) { sb.Append('&'); } else if (type.IsPointer) { sb.Append('*'); } else { Debug.Fail("Should not get here."); throw new InvalidOperationException(); //Unexpected error: Runtime Reflection is a trusted source so we should not have gotten here. } } else if (type.IsGenericParameter) { if (!withinGenericTypeArgument) { // This special rule causes generic type variables ("T") to serialize as "!T" (variable on type) or "!!T" (variable on method) // to distinguish them from a plain old type named "T". // // This rule does not kick in if we're serializing a type variable embedded inside a generic type argument list. (Fortunately, there // is no risk of ambiguity in that case because generic type argument lists always serialize plain old types as "[<assembly-qualified-name>]".) sb.Append('!'); if (type.DeclaringMethod != null) { sb.Append('!'); } } sb.Append(type.Name); } else { // If we got here, "type" is either a plain old type or a constructed generic type. if (withinGenericTypeArgument) { sb.Append('['); } Type plainOldType; Type[] instantiation; SplitIntoPlainOldTypeAndInstantiation(type, out plainOldType, out instantiation); sb.Append(plainOldType.FullName); if (instantiation != null) { sb.AppendGenericTypeArguments(instantiation); } if (withinGenericTypeArgument) { sb.Append(", "); sb.Append(plainOldType.Assembly.FullName); sb.Append(']'); } } }
public static string GetSignature(object obj) { if (obj == null) { return("Ljava/lang/Object;"); } System.Type c = !(obj is System.Type) ? obj.GetType() : ((System.Type)obj); if (c.IsPrimitive) { if (c.Equals(typeof(int))) { return("I"); } if (c.Equals(typeof(bool))) { return("Z"); } if (c.Equals(typeof(byte))) { return("B"); } if (c.Equals(typeof(short))) { return("S"); } if (c.Equals(typeof(long))) { return("J"); } if (c.Equals(typeof(float))) { return("F"); } if (c.Equals(typeof(double))) { return("D"); } if (!c.Equals(typeof(char))) { return(string.Empty); } return("C"); } if (c.Equals(typeof(string))) { return("Ljava/lang/String;"); } if (obj is AndroidJavaProxy) { AndroidJavaObject obj2 = new AndroidJavaObject(((AndroidJavaProxy)obj).javaInterface.GetRawClass()); return("L" + obj2.Call <string>("getName", new object[0]) + ";"); } if (c.Equals(typeof(AndroidJavaRunnable))) { return("Ljava/lang/Runnable;"); } if (c.Equals(typeof(AndroidJavaClass))) { return("Ljava/lang/Class;"); } if (c.Equals(typeof(AndroidJavaObject))) { if (obj == c) { return("Ljava/lang/Object;"); } AndroidJavaObject obj3 = (AndroidJavaObject)obj; using (AndroidJavaObject obj4 = obj3.Call <AndroidJavaObject>("getClass", new object[0])) { return("L" + obj4.Call <string>("getName", new object[0]) + ";"); } } if (typeof(Array).IsAssignableFrom(c)) { if (c.GetArrayRank() != 1) { throw new Exception("JNI: System.Array in n dimensions is not allowed"); } StringBuilder builder = new StringBuilder(); builder.Append('['); builder.Append(GetSignature(c.GetElementType())); return(builder.ToString()); } object[] objArray1 = new object[] { "JNI: Unknown signature for type '", c, "' (obj = ", obj, ") ", (c != obj) ? "instance" : "equal" }; throw new Exception(string.Concat(objArray1)); }
private Type ImportImpl(System.Type type) { if (type.Assembly == typeof(IKVM.Reflection.Type).Assembly) { throw new ArgumentException("Did you really want to import " + type.FullName + "?"); } if (type.HasElementType) { if (type.IsArray) { if (type.Name.EndsWith("[]")) { return(Import(type.GetElementType()).MakeArrayType()); } else { return(Import(type.GetElementType()).MakeArrayType(type.GetArrayRank())); } } else if (type.IsByRef) { return(Import(type.GetElementType()).MakeByRefType()); } else if (type.IsPointer) { return(Import(type.GetElementType()).MakePointerType()); } else { throw new InvalidOperationException(); } } else if (type.IsGenericParameter) { if (type.DeclaringMethod != null) { throw new NotImplementedException(); } else { return(Import(type.DeclaringType).GetGenericArguments()[type.GenericParameterPosition]); } } else if (type.IsGenericType && !type.IsGenericTypeDefinition) { System.Type[] args = type.GetGenericArguments(); Type[] importedArgs = new Type[args.Length]; for (int i = 0; i < args.Length; i++) { importedArgs[i] = Import(args[i]); } return(Import(type.GetGenericTypeDefinition()).MakeGenericType(importedArgs)); } else if (type.IsNested) { // note that we can't pass in the namespace here, because .NET's Type.Namespace implementation is broken for nested types // (it returns the namespace of the declaring type) return(Import(type.DeclaringType).ResolveNestedType(new TypeName(null, type.Name))); } else if (type.Assembly == typeof(object).Assembly) { // make sure mscorlib types always end up in our mscorlib return(Mscorlib.ResolveType(new TypeName(type.Namespace, type.Name))); } else { return(Import(type.Assembly).ResolveType(new TypeName(type.Namespace, type.Name))); } }
static void GetClassName(System.Type type, out string clsName, out string realClsName, out bool isByRef, bool simpleClassName = false) { isByRef = type.IsByRef; if (isByRef) { type = type.GetElementType(); } bool isArray = type.IsArray; int arrayCount = 1; if (isArray) { arrayCount = type.GetArrayRank(); type = type.GetElementType(); } string realNamespace = null; bool isNestedGeneric = false; if (type.IsNested) { string bClsName, bRealClsName; bool tmp; var rt = type.ReflectedType; if (rt.IsGenericType && rt.IsGenericTypeDefinition) { if (type.IsGenericType) { rt = rt.MakeGenericType(type.GetGenericArguments()); isNestedGeneric = true; } } if (rt == type) { wxb.L.LogErrorFormat("type:{0} -> {1}", type.Name, rt.Name); } GetClassName(rt, out bClsName, out bRealClsName, out tmp); clsName = simpleClassName ? "" : bClsName + "_"; realNamespace = bRealClsName + "."; } else { clsName = simpleClassName ? "" : (!string.IsNullOrEmpty(type.Namespace) ? type.Namespace.Replace(".", "_") + "_" : ""); realNamespace = !string.IsNullOrEmpty(type.Namespace) ? type.Namespace + "." : null; } clsName = clsName + type.Name.Replace(".", "_").Replace("`", "_").Replace("<", "_").Replace(">", "_"); bool isGeneric = false; string ga = null; if (type.IsGenericType && !isNestedGeneric) { isGeneric = true; clsName += "_"; ga = "<"; var args = type.GetGenericArguments(); bool first = true; foreach (var j in args) { if (first) { first = false; } else { clsName += "_"; ga += ", "; } string a, b; bool tmp; if (type == j) { wxb.L.LogErrorFormat("type:{0} -> {1}", type.Name, j.Name); } GetClassName(j, out a, out b, out tmp, true); clsName += a; ga += b; } ga += ">"; } if (!simpleClassName) { clsName += "_Binding"; } if (isArray) { clsName += "_Array"; } realClsName = realNamespace; if (isGeneric) { int idx = type.Name.IndexOf("`"); if (idx > 0) { realClsName += type.Name.Substring(0, idx); realClsName += ga; } else { realClsName += type.Name; } } else { realClsName += type.Name; } if (isArray) { if (arrayCount == 1) { realClsName += "[]"; } else { realClsName += "["; for (int i = 1; i < arrayCount; ++i) { realClsName += ","; } realClsName += "]"; } } }