GetGenericTypeDefinition() public method

Returns a T:System.Type object that represents a generic type definition from which the current generic type can be constructed.
The current type is not a generic type. That is, returns false. The invoked method is not supported in the base class. Derived classes must provide an implementation.
public GetGenericTypeDefinition ( ) : Type
return Type
Ejemplo n.º 1
0
        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");
            }
        }
        /// <summary>
        /// Returns any bindings from the specified collection that match the specified service.
        /// </summary>
        /// <param name="bindings">The multimap of all registered bindings.</param>
        /// <param name="service">The service in question.</param>
        /// <returns>The series of matching bindings.</returns>
        public IEnumerable<IBinding> Resolve(IDictionary<Type, IEnumerable<IBinding>> bindings, Type service)
        {
            if (!service.GetTypeInfo().IsGenericType || service.GetTypeInfo().IsGenericTypeDefinition || !bindings.ContainsKey(service.GetGenericTypeDefinition()))
                return Enumerable.Empty<IBinding>();

            return bindings[service.GetGenericTypeDefinition()];
        }
        internal static Func<PocketContainer, object> InMemoryEventSourcedRepositoryStrategy(Type type, PocketContainer container)
        {
            if (type.IsGenericType &&
                (type.GetGenericTypeDefinition() == typeof (IEventSourcedRepository<>) ||
                 type.GetGenericTypeDefinition() == typeof (InMemoryEventSourcedRepository<>)))
            {
                var aggregateType = type.GenericTypeArguments.Single();
                var repositoryType = typeof (InMemoryEventSourcedRepository<>).MakeGenericType(aggregateType);

                var streamName = AggregateType.EventStreamName(aggregateType);

                // get the single registered event stream instance
                var stream = container.Resolve<ConcurrentDictionary<string, IEventStream>>()
                                      .GetOrAdd(streamName,
                                                name => container.Clone()
                                                                 .Register(_ => name)
                                                                 .Resolve<IEventStream>());

                return c => Activator.CreateInstance(repositoryType, stream, c.Resolve<IEventBus>());
            }

            if (type == typeof (IEventStream))
            {
                return c => c.Resolve<InMemoryEventStream>();
            }

            return null;
        }
Ejemplo n.º 4
0
 public override bool CanConvert(Type objectType)
 {
     var canConvert = objectType.IsGenericType
                      && (objectType.GetGenericTypeDefinition() == typeof(Dictionary<,>) || objectType.GetGenericTypeDefinition() == typeof(IDictionary<,>))
                      && objectType.GetGenericArguments()[0] == typeof(Medicine);
     return canConvert;
 }
        /// <summary>
        /// Get a ILazyLoadProxy for a type, member name
        /// </summary>
        /// <param name="type">The target type which contains the member proxyfied</param>
        /// <returns>Return the ILazyLoadProxy instance</returns>
        public ILazyFactory GetLazyFactory(Type type)
        {
            if (type.IsInterface)
            {

                if (type.IsGenericType && (type.GetGenericTypeDefinition() == typeof(IList<>)))
                {
                    return _factory[type.GetGenericTypeDefinition()] as ILazyFactory;
                }
                else

                    if (type == typeof(IList))
                    {
                        return _factory[type] as ILazyFactory;
                    }
                    else
                    {
                        throw new DataMapperException("Cannot proxy others interfaces than IList or IList<>.");
                    }
            }
            else
            {
                // if you want to proxy concrete classes, there are also two requirements:
                // the class can not be sealed and only virtual methods can be intercepted.
                // The reason is that DynamicProxy will create a subclass of your class overriding all methods
                // so it can dispatch the invocations to the interceptor.
                return new LazyLoadProxyFactory();
            }
        }
Ejemplo n.º 6
0
		public static Type GetClosedParameterType(this AbstractTypeEmitter type, Type parameter)
		{
			if (parameter.IsGenericTypeDefinition)
			{
				return parameter.GetGenericTypeDefinition().MakeGenericType(type.GetGenericArgumentsFor(parameter));
			}

			if (parameter.IsGenericType)
			{
				var arguments = parameter.GetGenericArguments();
				if (CloseGenericParametersIfAny(type, arguments))
				{
					return parameter.GetGenericTypeDefinition().MakeGenericType(arguments);
				}
			}

			if (parameter.IsGenericParameter)
			{
				return type.GetGenericArgument(parameter.Name);
			}

			if (parameter.IsArray)
			{
				var elementType = GetClosedParameterType(type, parameter.GetElementType());
				return elementType.MakeArrayType();
			}

			if (parameter.IsByRef)
			{
				var elementType = GetClosedParameterType(type, parameter.GetElementType());
				return elementType.MakeByRefType();
			}

			return parameter;
		}
Ejemplo n.º 7
0
 public override bool CanConvert(Type objectType)
 {
     return objectType.IsGenericType
       &&
       (objectType.GetGenericTypeDefinition() == typeof(RawOrQueryDescriptor<>)
       || objectType.GetGenericTypeDefinition() == typeof(RawOrFilterDescriptor<>));
 }
Ejemplo n.º 8
0
        /// <summary>
        /// Returns any bindings from the specified collection that match the specified service.
        /// </summary>
        /// <param name="bindings">The multimap of all registered bindings.</param>
        /// <param name="service">The service in question.</param>
        /// <returns>The series of matching bindings.</returns>
        public IEnumerable<IBinding> Resolve(Multimap<Type, IBinding> bindings, Type service)
        {
            if (!service.IsGenericType || !bindings.ContainsKey(service.GetGenericTypeDefinition()))
                return Enumerable.Empty<IBinding>();

            return bindings[service.GetGenericTypeDefinition()].ToEnumerable();
        }
Ejemplo n.º 9
0
		private static string GetTypeName(Type array)
		{
			var element = array.IsArray
				? array.GetElementType()
				: array.IsGenericType && (array.GetGenericTypeDefinition() == typeof(List<>)
										|| array.GetGenericTypeDefinition() == typeof(HashSet<>))
					? array.GetGenericArguments()[0]
					: null;
			if (element == null)
				return null;
			if (element == typeof(string))
				return "\"-NGS-\".CLOB_ARR";
			if (element == typeof(bool) || element == typeof(bool?))
				return "\"-NGS-\".BOOL_ARR";
			if (element == typeof(int) || element == typeof(int?))
				return "\"-NGS-\".INT_ARR";
			if (element == typeof(decimal) || element == typeof(decimal?))
				return "\"-NGS-\".NUMBER_ARR";
			if (element == typeof(long) || element == typeof(long?))
				return "\"-NGS-\".LONG_ARR";
			if (element == typeof(float) || element == typeof(float?))
				return "\"-NGS-\".FLOAT_ARR";
			if (element == typeof(double) || element == typeof(double?))
				return "\"-NGS-\".DOUBLE_ARR";
			if (element == typeof(DateTime) || element == typeof(DateTime?))
				return "\"-NGS-\".TWTZ_ARR";
			if (element == typeof(Guid) || element == typeof(Guid?))
				return "\"-NGS-\".GUID_ARR";
			if (typeof(IAggregateRoot).IsAssignableFrom(element))
				return "\"" + element.Namespace + "\".\"-" + element.Name + "-EA-\"";
			if (typeof(IAggregateRoot).IsAssignableFrom(element))
				return "\"" + element.Namespace + "\".\"-" + element.Name + "-SA-\"";
			//TODO missing value types
			return null;
		}
        IEnumerable<MessageOwner> IMessageOwnersSelector.Of(Type type)
        {
            if(type.IsGenericType && (type.GetGenericTypeDefinition() == typeof(Request<>) || type.GetGenericTypeDefinition() == typeof(Reply<>)))
                return Of(type.GetGenericArguments()[0]);

            return Of(type);
        }
Ejemplo n.º 11
0
        /// <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);
            }
        }
Ejemplo n.º 12
0
        protected override object CreateDataSource( string name, Type type, NamedParameters ctorArgs )
        {
            var dataSources = (IList)typeof( List<> ).CreateGeneric( type );
            foreach ( var factory in Factories )
            {
                if ( factory.CanCreate( name, type ) )
                {
                    dataSources.Add( factory.Create( name, type, ctorArgs ) );
                }
            }

            var innerType = type.GetGenericArguments().First();
            if ( type.GetGenericTypeDefinition() == typeof( ISingleDataSource<> ) )
            {
                return typeof( StackSingleDataSource<> ).CreateGeneric( innerType, name, dataSources );
            }
            if ( type.GetGenericTypeDefinition() == typeof( IEnumerableDataSource<> ) )
            {
                return typeof( StackEnumerableDataSource<> ).CreateGeneric( innerType, name, dataSources );
            }
            else
            {
                throw new NotSupportedException();
            }
        }
		/// <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;
		}
Ejemplo n.º 14
0
        private static Type resolveGenericTypeDefinition(Type parent)
        {
            var shouldUseGenericType = !(parent.IsGenericType && parent.GetGenericTypeDefinition() != parent);

            if (parent.IsGenericType && shouldUseGenericType)
                parent = parent.GetGenericTypeDefinition();
            return parent;
        }
Ejemplo n.º 15
0
        /// <summary>
        /// Returns any bindings from the specified collection that match the specified service.
        /// </summary>
        /// <param name="bindings">The multimap of all registered bindings.</param>
        /// <param name="service">The service in question.</param>
        /// <returns>The series of matching bindings.</returns>
        public IEnumerable<IBinding> Resolve(Multimap<Type, IBinding> bindings, Type service)
        {
            if (!service.IsGenericType || !bindings.ContainsKey(service.GetGenericTypeDefinition()))
                yield break;

            Type gtd = service.GetGenericTypeDefinition();

            foreach (IBinding binding in bindings[gtd])
                yield return binding;
        }
Ejemplo n.º 16
0
        private static bool Accepted(Type t)
        {
            if (t.IsGenericType && t.GetGenericTypeDefinition() == typeof(EventDispatcher<>))
                return false;

            if (t.IsGenericType && t.GetGenericTypeDefinition() == typeof(CommandDispatcher<>))
                return false;

            return true;
        }
Ejemplo n.º 17
0
        private static void ProcessNestedGenericTypes(Type t, StringBuilder sb, bool fullName)
        {
            var genericFullName = t.GetGenericTypeDefinition().FullName;
            var genericSimpleName = t.GetGenericTypeDefinition().Name;
            var parts = genericFullName.Split('+');
            var genericArguments = t.GetTypeInfo().GenericTypeArguments;
            var index = 0;
            var totalParts = parts.Length;
            if (totalParts == 1)
            {
                var part = parts[0];
                var num = part.IndexOf('`');
                if (num == -1)
                {
                    return;
                }

                var name = part.Substring(0, num);
                var numberOfGenericTypeArgs = int.Parse(part.Substring(num + 1));
                sb.Append(fullName ? name : genericSimpleName.Substring(0, genericSimpleName.IndexOf('`')));
                AppendGenericArguments(genericArguments, index, numberOfGenericTypeArgs, sb, fullName);
                return;
            }
            for (var i = 0; i < totalParts; i++)
            {
                var part = parts[i];
                var num = part.IndexOf('`');
                if (num != -1)
                {
                    var name = part.Substring(0, num);
                    var numberOfGenericTypeArgs = int.Parse(part.Substring(num + 1));
                    if (fullName || (i == totalParts - 1))
                    {
                        sb.Append(name);
                        AppendGenericArguments(genericArguments, index, numberOfGenericTypeArgs, sb, fullName);
                    }
                    if (fullName && (i != totalParts - 1))
                    {
                        sb.Append("+");
                    }
                    index += numberOfGenericTypeArgs;
                }
                else
                {
                    if (fullName || (i == totalParts - 1))
                    {
                        sb.Append(part);
                    }
                    if (fullName && (i != totalParts - 1))
                    {
                        sb.Append("+");
                    }
                }
            }
        }
Ejemplo n.º 18
0
        public object Parse(Type type, XObject config, bool isAssignableTypeAllowed, XmlLocation childLocation, IContext context)
        {
            var configEl = config as XElement;
            if (configEl == null)
                throw new TestLibsException($"Following configuration element:\n{config}\n\tcouldn't be cast to type: {type}. XElement expected");
            
            var genArgs = type.GetGenericArguments();

            if (genArgs.Length > 2)
                throw new TestLibsException($"Unsupported type: {type.ToString()}. Couldn't parse following config to that type:\n{configEl}");

            var childObjType = genArgs.Last();
            var childObjs = XmlParser.Parse(childObjType, configEl, childLocation, isAssignableTypeAllowed, context);

            var propertyObj = Activator.CreateInstance(type);

            if (type.GetGenericTypeDefinition() == typeof(List<>))
            {
                var add = type.GetMethod("Add", new[] { childObjType });

                foreach (var child in childObjs)
                {
                    add.Invoke(propertyObj, new object[] { child });
                }
            }
            else if (type.GetGenericTypeDefinition() == typeof(LinkedList<>))
            {
                var add = type.GetMethod("AddLast", new[] { childObjType });

                foreach (var child in childObjs)
                {
                    add.Invoke(propertyObj, new object[] { child });
                }
            }
            else if (type.GetGenericTypeDefinition() == typeof(Dictionary<,>))
            {
                var childXmlType = ReflectionManager.GetXmlType(childObjType);
                if (childXmlType == null)
                    throw new TestLibsException($"Couldn't parse type: {type} to dictionary, because child type: {childObjType} isn't XmlType");

                var add = type.GetMethod("Add", new[] { childXmlType.KeyProperty.PropertyType, childObjType });

                foreach (var child in childObjs)
                {
                    var key = childXmlType.KeyProperty.GetValue(child);
                    add.Invoke(propertyObj, new object[] { key, child });
                }
            }
            else
            {
                throw new TestLibsException($"Unsupported generic type: {type}. Couldn't parse following config to that type:\n{configEl}");
            }

            return propertyObj;
        }
 public static bool IsArrayOrEnumerable(Type type)
 {
     return type.IsArray || (type.IsGenericType &&
                             (type.GetGenericTypeDefinition() == typeof (IEnumerable<>)
                              || type.GetGenericTypeDefinition() == typeof (ICollection<>)
                              || type.GetGenericTypeDefinition() == typeof (Collection<>)
                              || type.GetGenericTypeDefinition() == typeof (IList<>)
                              || type.GetGenericTypeDefinition() == typeof (List<>)
                                 )
         );
 }
Ejemplo n.º 20
0
        /// <summary>
        ///     Adds the type.
        /// </summary>
        /// <param name="type">The type.</param>
        public void AddType(Type type)
        {
            if (type == null)
                return;

            if (_typesRepository.Exist(type)) return;

            if (type.IsGenericType && (typeof (IEnumerable<>).IsAssignableFrom(type.GetGenericTypeDefinition())
                                       || typeof (IList<>).IsAssignableFrom(type.GetGenericTypeDefinition())))
            {
                AddType(type.GetElementType());

                foreach (Type interfaceType in type.GetInterfaces())
                {
                    foreach (Type genericArgument in interfaceType.GetGenericArguments())
                    {
                        AddType(genericArgument);
                    }
                }

                return;
            }

            if (type.IsSimpleType())
                return;

            //var typeclousure = type;
            SpinWait.SpinUntil(() => !_spinLockProcessedTypes.IsHeld);
            if (_processedTypes.Contains(type))
                return;
            bool lockTaken = false;
            _spinLockProcessedTypes.Enter(ref lockTaken);
            if (lockTaken)
            {
                try
                {
                    if (!_processedTypes.Contains(type))
                        _processedTypes.Add(type);
                    else
                    {
                        return;
                    }
                }
                finally
                {
                    _spinLockProcessedTypes.Exit();
                }
            }

            AddPropertiesAndFileds(type);
            _typesRepository.Add(type);
        }
Ejemplo n.º 21
0
        public static bool IsNullableType(Type type)
        {
            if (type == null)
            {
                return false;
            }

#if !WINRT
            return (type.IsGenericType && type.GetGenericTypeDefinition() == typeof (Nullable<>));
#else
						return (type.GetTypeInfo().IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>));
#endif
        }
        internal static Func<PocketContainer, object> InMemoryEventSourcedRepositoryStrategy(Type type, PocketContainer container)
        {
            if (type.IsGenericType &&
                (type.GetGenericTypeDefinition() == typeof (IEventSourcedRepository<>) ||
                 type.GetGenericTypeDefinition() == typeof (InMemoryEventSourcedRepository<>)))
            {
                var aggregateType = type.GenericTypeArguments.Single();
                var repositoryType = typeof (InMemoryEventSourcedRepository<>).MakeGenericType(aggregateType);
                return c => Activator.CreateInstance(repositoryType,
                                                     c.Resolve<InMemoryEventStream>(),
                                                     c.Resolve<IEventBus>());
            }

            return null;
        }
Ejemplo n.º 23
0
        // This method takes generic type and returns a 'partially' generic type definition of that same type,
        // where all generic arguments up to the given nesting level. This allows us to group generic types
        // by their partial generic type definition, which allows a much nicer user experience.
        internal static Type MakeTypePartiallyGenericUpToLevel(Type type, int nestingLevel)
        {
            if (nestingLevel > 100)
            {
                // Stack overflow prevention
                throw new ArgumentException("nesting level bigger than 100 too high. Type: " +
                    type.ToFriendlyName(), nameof(nestingLevel));
            }

            // example given type: IEnumerable<IQueryProcessor<MyQuery<Alpha>, int[]>>
            // nestingLevel 4 returns: IEnumerable<IQueryHandler<MyQuery<Alpha>, int[]>
            // nestingLevel 3 returns: IEnumerable<IQueryHandler<MyQuery<Alpha>, int[]>
            // nestingLevel 2 returns: IEnumerable<IQueryHandler<MyQuery<T>, int[]>
            // nestingLevel 1 returns: IEnumerable<IQueryHandler<TQuery, TResult>>
            // nestingLevel 0 returns: IEnumerable<T>
            if (!type.IsGenericType)
            {
                return type;
            }

            if (nestingLevel == 0)
            {
                return type.GetGenericTypeDefinition();
            }

            return MakeTypePartiallyGeneric(type, nestingLevel);
        }
        /// <summary>
        /// Gets the default implementation for a type.
        /// </summary>
        /// <param name="type">The type.</param>
        /// <returns>The type of the implem or the same type as input if there is no default implementation</returns>
        public static Type GetDefaultImplementation(Type type)
        {
            if (type == null)
                return null;

            // TODO change this code. Make it configurable?
            if (type.IsInterface)
            {
                Type implementationType;
                if (type.IsGenericType)
                {
                    if (DefaultInterfaceImplementations.TryGetValue(type.GetGenericTypeDefinition(), out implementationType))
                    {
                        type = implementationType.MakeGenericType(type.GetGenericArguments());
                    }
                }
                else
                {
                    if (DefaultInterfaceImplementations.TryGetValue(type, out implementationType))
                    {
                        type = implementationType;
                    }
                }
            }
            return type;
        }
Ejemplo n.º 25
0
    /// <summary>
    /// Determines whether this instance can convert the specified object type.
    /// </summary>
    /// <param name="objectType">Type of the object.</param>
    /// <returns>
    ///     <c>true</c> if this instance can convert the specified object type; otherwise, <c>false</c>.
    /// </returns>
    public override bool CanConvert(Type objectType)
    {
      if (objectType.IsValueType && objectType.IsGenericType)
        return (objectType.GetGenericTypeDefinition() == typeof (KeyValuePair<,>));

      return false;
    }
Ejemplo n.º 26
0
 private bool IsTypeGenericDictionaryInterface(Type type)
 {
   if (!TypeExtensions.IsGenericType(type))
     return false;
   else
     return type.GetGenericTypeDefinition() == typeof (IDictionary<,>);
 }
Ejemplo n.º 27
0
 static object ConvertStringToNewType(object value, Type newType)
 {
     // If it's not a nullable type, just pass through the parameters to Convert.ChangeType
     if (newType.IsGenericType && newType.GetGenericTypeDefinition() == typeof(Nullable<>))
         return value == null ? null : ConvertStringToNewNonNullableType(value, new NullableConverter(newType).UnderlyingType);
     return ConvertStringToNewNonNullableType(value, newType);
 }
Ejemplo n.º 28
0
 public static bool CanAssignFromGenericType(string serializedTypeString, Type t)
 {
     SerializedTypeData data = SplitTypeString(serializedTypeString);
     if (!data.isGeneric)
     {
         return false;
     }
     if (t.IsGenericType)
     {
         if ((data.typeName == "T") || (data.typeName == "T[]"))
         {
             return false;
         }
         Type[] genericArguments = t.GetGenericArguments();
         if (genericArguments.Length != 1)
         {
             return false;
         }
         if (genericArguments[0].IsGenericType)
         {
             return false;
         }
         return (t.GetGenericTypeDefinition() == FromString(data).GetGenericTypeDefinition());
     }
     return ((data.typeName == "T") || (data.typeName == "T[]"));
 }
    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);
    }
        private Type DetermineParameterValueType(Type parameterType)
        {
            // if the parameter is a generic collection.
            if (parameterType.IsGenericType && typeof(IEnumerable).IsAssignableFrom(parameterType))
            {
                Type genericEnumerableType = null;
                if (typeof(IEnumerable<>).IsAssignableFrom(parameterType.GetGenericTypeDefinition()))
                {
                    genericEnumerableType = parameterType;
                }
                else
                {
                    genericEnumerableType = (from interfaceType in parameterType.GetInterfaces()
                                             where interfaceType.IsGenericType
                                             where typeof(IEnumerable<>)
                                             .IsAssignableFrom(interfaceType.GetGenericTypeDefinition())
                                             select interfaceType).Single();
                }

                return genericEnumerableType.GetGenericArguments().Single();
            }
            else
            {
                return parameterType;
            }
        }
Ejemplo n.º 31
0
    static bool GetBaseType(System.Type type, System.Type baseType)
    {
        if (type == null || baseType == null || type == baseType)
        {
            return(false);
        }

        if (baseType.IsGenericType == false)
        {
            if (type.IsGenericType == false)
            {
                return(type.IsSubclassOf(baseType));
            }
        }
        else
        {
            baseType = baseType.GetGenericTypeDefinition();
        }

        type = type.BaseType;
        System.Type objectType = typeof(object);
        while (type != objectType && type != null)
        {
            System.Type curentType = type.IsGenericType ?
                                     type.GetGenericTypeDefinition() : type;
            if (curentType == baseType)
            {
                return(true);
            }

            type = type.BaseType;
        }

        return(false);
    }
        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);
        }
    public override void OnGUI(Rect _position, SerializedProperty _property, GUIContent _label)
    {
        Object             asset             = null;
        SerializedProperty assetGUIDProperty = _property.FindPropertyRelative("assetGUID");

        if (!string.IsNullOrEmpty(assetGUIDProperty.stringValue))
        {
            asset = GUIDToAsset(assetGUIDProperty.stringValue, NamedAttribute.resourceType);
        }

        Object newAsset = EditorGUI.ObjectField(_position, UpperSeparatedName(_property.name), asset, NamedAttribute.resourceType, false);

        if (asset != newAsset)
        {
            object   current = _property.serializedObject.targetObject;
            string[] fields  = _property.propertyPath.Split('.');

            for (int i = 0; i < fields.Length; i++)
            {
                string fieldName = fields[i];

                if (fieldName.Equals("Array"))
                {
                    fieldName = fields[++i];
                    string indexString = fieldName.Substring(5, fieldName.Length - 6);
                    int    index       = int.Parse(indexString);

                    System.Type type = current.GetType();
                    if (type.IsArray)
                    {
                        System.Array array = current as System.Array;
                        current = array.GetValue(index);
                    }
                    else if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(List <>))
                    {
                        IList list = current as IList;
                        current = list[index];
                    }
                }
                else
                {
                    FieldInfo field = current.GetType().GetField(fields[i], BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
                    current = field.GetValue(current);
                }
            }

            AssetLink obj = current as AssetLink;
            SetAsset.Invoke(obj, new object[] { newAsset });
//			obj.asset = newAsset;
            _property.serializedObject.ApplyModifiedProperties();

            EditorUtility.SetDirty(_property.serializedObject.targetObject);
        }
    }
Ejemplo n.º 34
0
 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);
 }
Ejemplo n.º 35
0
 private static bool HasGenericBase(System.Type myType, System.Type t)
 {
     Debug.Assert(t.IsGenericTypeDefinition);
     while (myType != typeof(object))
     {
         if (myType.IsGenericType && myType.GetGenericTypeDefinition() == t)
         {
             return(true);
         }
         myType = myType.BaseType;
     }
     return(false);
 }
Ejemplo n.º 36
0
    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);
    }
Ejemplo n.º 37
0
    public static Key GetCollectionType(System.Type type)
    {
        if (!ES2Reflection.IsAssignableFrom(typeof(IEnumerable), type))
        {
            return(Key._Null);
        }

        if (type.IsArray)
        {
            return(Key._NativeArray);
        }

        // If it's not an array and doesn't have generic arguments, we don't consider it to be a collection.
        if (!ES2Reflection.IsGenericType(type))
        {
            return(Key._Null);
        }

        System.Type genericType = type.GetGenericTypeDefinition();

        if (genericType == typeof(Dictionary <,>))
        {
            return(Key._Dictionary);
        }
        else if (genericType == typeof(List <>))
        {
            return(Key._List);
        }
        else if (genericType == typeof(Queue <>))
        {
            return(Key._Queue);
        }
        else if (genericType == typeof(Stack <>))
        {
            return(Key._Stack);
        }
        if (genericType == typeof(HashSet <>))
        {
            return(Key._HashSet);
        }

        return(Key._Null);
    }
Ejemplo n.º 38
0
    public static Object GetDefaultAssetForReferenceType(System.Type type)
    {
        if (type.IsAbstract)
        {
            return(null);
        }

        if (typeof(SettingsReferenceBase).IsAssignableFrom(type))
        {
            while (type != null)
            {
                if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(SettingsReference <>))
                {
                    var assetType = type.GetGenericArguments()[0];                     // will be derived from SettingsAsset<T>
                    var property  = assetType.GetProperty("defaultInstance",
                                                          BindingFlags.Static | BindingFlags.Public | BindingFlags.FlattenHierarchy);
                    return(property.GetValue(null, null) as Object);
                }
                type = type.BaseType;
            }
        }

        return(null);
    }
Ejemplo n.º 39
0
 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));
     }
 }
Ejemplo n.º 40
0
        /// <summary>
        /// 从字符串中获取值
        /// </summary>
        /// <param name="value"></param>
        /// <param name="type"></param>
        /// <returns></returns>
        public static object TryGetValue(this string value, System.Type type, object defultValue)
        {
            try
            {
                if (type == null)
                {
                    return("");
                }
                if (string.IsNullOrEmpty(value))
                {
                    return(type.IsValueType ? Activator.CreateInstance(type) : null);
                }

                if (type == typeof(string))
                {
                    return(value);
                }
                if (type == typeof(int))
                {
                    return(Convert.ToInt32(Convert.ToDouble(value)));
                }
                if (type == typeof(float))
                {
                    return(float.Parse(value));
                }
                if (type == typeof(byte))
                {
                    return(Convert.ToByte(Convert.ToDouble(value)));
                }
                if (type == typeof(sbyte))
                {
                    return(Convert.ToSByte(Convert.ToDouble(value)));
                }
                if (type == typeof(uint))
                {
                    return(Convert.ToUInt32(Convert.ToDouble(value)));
                }
                if (type == typeof(short))
                {
                    return(Convert.ToInt16(Convert.ToDouble(value)));
                }
                if (type == typeof(long))
                {
                    return(Convert.ToInt64(Convert.ToDouble(value)));
                }
                if (type == typeof(ushort))
                {
                    return(Convert.ToUInt16(Convert.ToDouble(value)));
                }
                if (type == typeof(ulong))
                {
                    return(Convert.ToUInt64(Convert.ToDouble(value)));
                }
                if (type == typeof(double))
                {
                    return(double.Parse(value));
                }
                if (type == typeof(bool))
                {
                    return(bool.Parse(value));
                }
                if (type.BaseType == typeof(Enum))
                {
                    return(GetValue(value, Enum.GetUnderlyingType(type)));
                }
                if (type == typeof(Vector2))
                {
                    Vector2 vector;
                    ParseVector2(value, out vector);
                    return(vector);
                }
                if (type == typeof(Vector3))
                {
                    Vector3 vector;
                    ParseVector3(value, out vector);
                    //Debug.LogError(vector.ToString());
                    return(vector);
                }
                if (type == typeof(Vector4))
                {
                    Vector4 vector;
                    ParseVector4(value, out vector);
                    return(vector);
                }
                if (type == typeof(Quaternion))
                {
                    Quaternion quaternion;
                    ParseQuaternion(value, out quaternion);
                    return(quaternion);
                }
                if (type == typeof(Color))
                {
                    Color color;
                    ParseColor(value, out color);
                    return(color);
                }

                object constructor;
                object genericArgument;
                //词典
                if (type.IsGenericType && (type.GetGenericTypeDefinition() == typeof(Dictionary <,>)))
                {
                    System.Type[] genericArguments         = type.GetGenericArguments();
                    Dictionary <string, string> dictionary = ParseMap(value, Spriter2, Spriter1);
                    constructor = type.GetConstructor(System.Type.EmptyTypes).Invoke(null);
                    foreach (KeyValuePair <string, string> pair in dictionary)
                    {
                        object genericArgument1 = GetValue(pair.Key, genericArguments[0]);
                        genericArgument = GetValue(pair.Value, genericArguments[1]);
                        type.GetMethod("Add").Invoke(constructor, new object[] { genericArgument1, genericArgument });
                    }
                    return(constructor);
                }
                //列表
                if (type.IsGenericType && (type.GetGenericTypeDefinition() == typeof(List <>)))
                {
                    System.Type   type2 = type.GetGenericArguments()[0];
                    List <string> list  = ParseList(value, Spriter1);

                    constructor = Activator.CreateInstance(type);
                    foreach (string str in list)
                    {
                        genericArgument = GetValue(str, type2);
                        Debug.Log(str + "  " + type2.Name);
                        type.GetMethod("Add").Invoke(constructor, new object[] { genericArgument });
                    }
                    return(constructor);
                }
                if (type == typeof(ArrayList))
                {
                    return(value.GetValue <List <string> >() ?? defultValue);
                }
                if (type == typeof(Hashtable))
                {
                    return(value.GetValue <Dictionary <string, string> >() ?? defultValue);
                }
                //数组
                if (type.IsArray)
                {
                    Type elementType = Type.GetType(
                        type.FullName.Replace("[]", string.Empty));
                    string[] elStr = value.Split(Spriter1);
                    Array    array = Array.CreateInstance(elementType, elStr.Length);

                    for (int i = 0; i < elStr.Length; i++)
                    {
                        array.SetValue(elStr[i].GetValue(elementType), i);
                    }
                    return(array);
                }
                if (CanConvertFromString(type))
                {
                    return(ParseFromStringableObject(value, type));
                }

                Debug.unityLogger.LogWarning("字符转换", "没有适合的转换类型,返回默认值");
                if (defultValue != type.DefaultForType())
                {
                    return(defultValue);
                }
                return(type.DefaultForType());
            }
            catch (Exception e)
            {
                Debug.unityLogger.LogException(e);
                Debug.unityLogger.LogWarning("字符转换", "解析失败,返回默认值");
                return(type.DefaultForType());
            }
        }
 public bool Deserialize()
 {
     if (this._data == null)
     {
         this._result = DeserializeResult.NoData;
         return(false);
     }
     if (this._result == DeserializeResult.Success)
     {
         return(true);
     }
     try
     {
         this._data.position = (int)this._offset;
         ushort num1 = this._data.ReadUShort();
         for (int index = 0; index < (int)num1; ++index)
         {
             string      str         = this._data.ReadString();
             ClassMember classMember = (ClassMember)null;
             System.Type key         = (System.Type)null;
             if (str.StartsWith("@"))
             {
                 if (this._extraProperties == null)
                 {
                     this._extraProperties = new MultiMap <string, object>();
                 }
                 byte num2 = this._data.ReadByte();
                 if (((int)num2 & 1) != 0)
                 {
                     byte num3 = (byte)((uint)num2 >> 1);
                     BinaryClassMember.typeMap.TryGetKey(num3, out key);
                 }
                 else
                 {
                     key = Editor.GetType(this._data.ReadString());
                 }
                 str = str.Substring(1, str.Length - 1);
             }
             else
             {
                 classMember = Editor.GetMember(this.GetType(), str);
                 if (classMember != null)
                 {
                     key = classMember.type;
                 }
             }
             uint num4 = this._data.ReadUInt();
             if (key != (System.Type)null)
             {
                 int position = this._data.position;
                 if (typeof(BinaryClassChunk).IsAssignableFrom(key))
                 {
                     BinaryClassChunk binaryClassChunk = BinaryClassChunk.DeserializeHeader(key, this._data, root: false);
                     if (classMember == null)
                     {
                         this._extraProperties.Add(str, (object)binaryClassChunk);
                     }
                     else
                     {
                         this._headerDictionary[str] = binaryClassChunk;
                     }
                     this._data.position = position + (int)num4;
                 }
                 else if (key.IsArray)
                 {
                     Array array = this.DeserializeArray(key, key.GetElementType(), this._data);
                     if (classMember == null)
                     {
                         this._extraProperties.Add(str, (object)array);
                     }
                     else
                     {
                         classMember.SetValue((object)this, (object)array);
                     }
                 }
                 else if (key.IsGenericType && key.GetGenericTypeDefinition() == typeof(List <>))
                 {
                     Array array    = this.DeserializeArray(typeof(object[]), key.GetGenericArguments()[0], this._data);
                     IList instance = Activator.CreateInstance(key) as IList;
                     foreach (object obj in array)
                     {
                         instance.Add(obj);
                     }
                     if (classMember == null)
                     {
                         this._extraProperties.Add(str, (object)instance);
                     }
                     else
                     {
                         classMember.SetValue((object)this, (object)instance);
                     }
                 }
                 else if (key.IsGenericType && key.GetGenericTypeDefinition() == typeof(HashSet <>))
                 {
                     Array array     = this.DeserializeArray(typeof(object[]), key.GetGenericArguments()[0], this._data);
                     IList instance1 = (IList)Activator.CreateInstance(typeof(List <>).MakeGenericType(key.GetGenericArguments()[0]));
                     foreach (object obj in array)
                     {
                         instance1.Add(obj);
                     }
                     object instance2 = Activator.CreateInstance(key, (object)instance1);
                     if (classMember == null)
                     {
                         this._extraProperties.Add(str, instance2);
                     }
                     else
                     {
                         classMember.SetValue((object)this, instance2);
                     }
                 }
                 else
                 {
                     object element = !key.IsEnum ? this._data.Read(key, false) : (object)this._data.ReadInt();
                     if (classMember == null)
                     {
                         this._extraProperties.Add(str, element);
                     }
                     else
                     {
                         classMember.SetValue((object)this, element);
                     }
                 }
             }
             else
             {
                 this._data.position += (int)num4;
             }
         }
     }
     catch (Exception ex)
     {
         this._exception = ex;
         this._result    = DeserializeResult.ExceptionThrown;
         return(false);
     }
     this._result = DeserializeResult.Success;
     return(true);
 }
Ejemplo n.º 42
0
        public static void ValidateEqual(BuildXLContext context, Type type, object expected, object actual, string objPath, Remapper remapper)
        {
            type = GetNonNullableType(type);

            if (type == typeof(bool))
            {
                XAssert.AreEqual((bool)expected, (bool)actual, $"{nameof(Boolean)} values don't match for objPath: {objPath}");
                return;
            }

            if (type == typeof(int) || type == typeof(short) || type == typeof(sbyte) || type == typeof(long))
            {
                XAssert.AreEqual(
                    Convert.ToInt64(expected),
                    Convert.ToInt64(actual),
                    $"Numeric values don't match for objPath: {objPath}");
                return;
            }

            if (type == typeof(uint) || type == typeof(ushort) || type == typeof(byte) || type == typeof(ulong))
            {
                XAssert.AreEqual(
                    Convert.ToUInt64(expected),
                    Convert.ToUInt64(actual),
                    $"Numeric values don't match for objPath: {objPath}");
                return;
            }

            if (type == typeof(double))
            {
                XAssert.AreEqual(
                    Convert.ToDouble(expected),
                    Convert.ToDouble(actual),
                    $"Numeric values don't match for objPath: {objPath}");
                return;
            }

            if (type == typeof(string))
            {
                XAssert.AreEqual((string)expected, (string)actual, $"{nameof(String)} values don't match for objPath: {objPath}");
                return;
            }

            if (type == typeof(ModuleId))
            {
                XAssert.AreEqual(
                    (ModuleId)expected,
                    (ModuleId)actual,
                    $"{nameof(ModuleId)} id values don't match for objPath: {objPath}");
                return;
            }

            if (type == typeof(LocationData))
            {
                AssertEqualLocationData(context, objPath, remapper, (LocationData)expected, (LocationData)actual);
                return;
            }

            if (type == typeof(RelativePath))
            {
                AssertEqualRelativePaths(context, objPath, remapper, (RelativePath)expected, (RelativePath)actual);
                return;
            }

            if (type == typeof(AbsolutePath))
            {
                AssertEqualAbsolutePaths(context, objPath, remapper, (AbsolutePath)expected, (AbsolutePath)actual);
                return;
            }

            if (type == typeof(FileArtifact))
            {
                AssertEqualFileArtifacts(context, objPath, remapper, (FileArtifact)expected, (FileArtifact)actual);
                return;
            }

            if (type == typeof(PathAtom))
            {
                AssertEqualPathAtoms(context, objPath, remapper, (PathAtom)expected, (PathAtom)actual);
                return;
            }

            if (type == typeof(SymbolAtom))
            {
                XAssert.AreEqual((SymbolAtom)expected, (SymbolAtom)actual, $"{nameof(SymbolAtom)} values don't match for objPath: {objPath}");
                return;
            }

            if (type == typeof(global::BuildXL.Utilities.LineInfo))
            {
                XAssert.AreEqual(
                    (global::BuildXL.Utilities.LineInfo)expected,
                    (global::BuildXL.Utilities.LineInfo)actual,
                    $"{nameof(global::BuildXL.Utilities.LineInfo)} values don't match for objPath: {objPath}");
                return;
            }

            if (type == typeof(LineInfo))
            {
                XAssert.AreEqual(
                    (LineInfo)expected,
                    (LineInfo)actual,
                    $"{nameof(LineInfo)} values don't match for objPath: {objPath}");
                return;
            }

            if (type.GetTypeInfo().IsEnum)
            {
                XAssert.AreEqual((Enum)expected, (Enum)actual, $"Enum values don't match for objPath: {objPath}");
                return;
            }

            if (type.GetTypeInfo().IsGenericType)
            {
                var generic = type.GetGenericTypeDefinition();
                if (generic == typeof(List <>) || generic == typeof(IReadOnlyList <>))
                {
                    XAssert.IsTrue((expected == null) == (actual == null));

                    var expectedList = expected as IList;
                    var actualList   = actual as IList;

                    XAssert.IsTrue(
                        (expectedList == null) == (actualList == null),
                        "One of the lists is null, the other isn't for objPath: {0}",
                        objPath);
                    if (expectedList != null)
                    {
                        XAssert.AreEqual(expectedList.Count, actualList.Count, $"Counts of lists don't match for objPath: {objPath}");
                        for (int i = 0; i < expectedList.Count; i++)
                        {
                            ValidateEqual(
                                context,
                                type.GenericTypeArguments[0],
                                expectedList[i],
                                actualList[i],
                                objPath + "[" + i.ToString(CultureInfo.InvariantCulture) + "]",
                                remapper);
                        }
                    }

                    return;
                }

                if (generic == typeof(Dictionary <,>) || generic == typeof(IReadOnlyDictionary <,>) || generic == typeof(ConcurrentDictionary <,>))
                {
                    XAssert.IsTrue((expected == null) == (actual == null));

                    var expectedDictionary = expected as IDictionary;
                    var actualDictionary   = actual as IDictionary;

                    XAssert.IsTrue(
                        (expectedDictionary == null) == (actualDictionary == null),
                        $"One of the dictionaries is null, the other isn't for objPath: {objPath}");
                    if (expectedDictionary != null)
                    {
                        XAssert.AreEqual(
                            expectedDictionary.Count,
                            expectedDictionary.Count,
                            $"Counts of dictionaries don't match for objPath: {objPath}");
                        foreach (var kv in expectedDictionary)
                        {
                            var key         = kv.GetType().GetProperty("Key").GetValue(kv);
                            var value       = kv.GetType().GetTypeInfo().GetProperty("Value").GetValue(kv);
                            var actualValue = actualDictionary[key];

                            ValidateEqual(context, type.GenericTypeArguments[1], value, actualValue, objPath + "[" + key + "]", remapper);
                        }
                    }

                    return;
                }
            }

            if (type.GetTypeInfo().IsInterface)
            {
                var actualType = ConfigurationConverter.FindImplementationType(
                    type,
                    ObjectLiteral.Create(new List <Binding>(), default(LineInfo), AbsolutePath.Invalid),

                    // Note we only create a sourceresolver, so no need to fiddle, just compare with SourceResolver.
                    () => "SourceResolver");
                ValidateEqualMembers(context, actualType, expected, actual, objPath, remapper);
                return;
            }

            if (type.GetTypeInfo().IsClass)
            {
                ValidateEqualMembers(context, type, expected, actual, objPath, remapper);
                return;
            }

            XAssert.Fail($"Don't know how to compare objects of this type '{type}' for objPath: {objPath}");
        }
Ejemplo n.º 43
0
 public static bool isDict(System.Type t)
 {
     return(t.IsGenericType && t.GetGenericTypeDefinition() == typeof(Dictionary <,>));
 }
Ejemplo n.º 44
0
 /// <summary>
 /// Determines whether the specified type is Nullable.
 /// </summary>
 /// <param name="type">The type.</param>
 /// <returns>True, if the type is nullable, false otherwise.</returns>
 private static bool IsNullable(SystemType type)
 {
     return type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>);
 }
Ejemplo n.º 45
0
        private static (object?, InvalidOperationException?) TryConvertObject(string context, object?val, System.Type targetType)
        {
            var targetIsNullable = targetType.IsGenericType && targetType.GetGenericTypeDefinition() == typeof(Nullable <>);

            // Note: 'null's can enter the system as the representation of an 'unknown' value.
            // Before calling 'Convert' we will have already lifted the 'IsKnown' bit out, but we
            // will be passing null around as a value.
            if (val == null)
            {
                if (targetIsNullable)
                {
                    // A 'null' value coerces to a nullable null.
                    return(null, null);
                }

                if (targetType.IsValueType)
                {
                    return(Activator.CreateInstance(targetType), null);
                }

                // for all other types, can just return the null value right back out as a legal
                // reference type value.
                return(null, null);
            }

            // We're not null and we're converting to Nullable<T>, just convert our value to be a T.
            if (targetIsNullable)
            {
                return(TryConvertObject(context, val, targetType.GenericTypeArguments.Single()));
            }

            if (targetType == typeof(string))
            {
                return(TryEnsureType <string>(context, val));
            }

            if (targetType == typeof(bool))
            {
                return(TryEnsureType <bool>(context, val));
            }

            if (targetType == typeof(double))
            {
                return(TryEnsureType <double>(context, val));
            }

            if (targetType == typeof(int))
            {
                var(d, exception) = TryEnsureType <double>(context, val);
                if (exception != null)
                {
                    return(null, exception);
                }

                return((int)d, exception);
            }

            if (targetType == typeof(Asset))
            {
                return(TryEnsureType <Asset>(context, val));
            }

            if (targetType == typeof(Archive))
            {
                return(TryEnsureType <Archive>(context, val));
            }

            if (targetType == typeof(AssetOrArchive))
            {
                return(TryEnsureType <AssetOrArchive>(context, val));
            }

            if (targetType == typeof(JsonElement))
            {
                return(TryConvertJsonElement(context, val));
            }

            if (targetType.IsConstructedGenericType)
            {
                if (targetType.GetGenericTypeDefinition() == typeof(Union <,>))
                {
                    return(TryConvertOneOf(context, val, targetType));
                }

                if (targetType.GetGenericTypeDefinition() == typeof(ImmutableArray <>))
                {
                    return(TryConvertArray(context, val, targetType));
                }

                if (targetType.GetGenericTypeDefinition() == typeof(ImmutableDictionary <,>))
                {
                    return(TryConvertDictionary(context, val, targetType));
                }

                throw new InvalidOperationException(
                          $"Unexpected generic target type {targetType.FullName} when deserializing {context}");
            }

            if (targetType.GetCustomAttribute <OutputTypeAttribute>() == null)
            {
                return(null, new InvalidOperationException(
                           $"Unexpected target type {targetType.FullName} when deserializing {context}"));
            }

            var constructor = GetPropertyConstructor(targetType);

            if (constructor == null)
            {
                return(null, new InvalidOperationException(
                           $"Expected target type {targetType.FullName} to have [{nameof(OutputConstructorAttribute)}] constructor when deserializing {context}"));
            }

            var(dictionary, tempException) = TryEnsureType <ImmutableDictionary <string, object> >(context, val);
            if (tempException != null)
            {
                return(null, tempException);
            }

            var constructorParameters = constructor.GetParameters();
            var arguments             = new object?[constructorParameters.Length];

            for (int i = 0, n = constructorParameters.Length; i < n; i++)
            {
                var parameter = constructorParameters[i];

                // Note: TryGetValue may not find a value here.  That can happen for things like
                // unknown vals.  That's ok.  We'll pass that through to 'Convert' and will get the
                // default value needed for the parameter type.
                dictionary !.TryGetValue(parameter.Name !, out var argValue);
                var(temp, tempException1) = TryConvertObject($"{targetType.FullName}({parameter.Name})", argValue, parameter.ParameterType);
                if (tempException1 != null)
                {
                    return(null, tempException1);
                }

                arguments[i] = temp;
            }

            return(constructor.Invoke(arguments), null);
        }
Ejemplo n.º 46
0
 public static bool IsEnumerableOfT(this System.Type type)
 {
     return(type.IsGenericType && type.GetGenericTypeDefinition() == typeof(IEnumerable <>));
 }
Ejemplo n.º 47
0
        /// <summary>
        /// 将值转化为字符串
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static string ConverToString(this object value)
        {
            //Debug.logger.Log("ConverToString " + Spriter1 + "  "+ Spriter2);
            if (value == null)
            {
                return(string.Empty);
            }
            System.Type type = value.GetType();
            if (type == null)
            {
                return(string.Empty);
            }
            if (type == typeof(Vector3))
            {
                return(FBracket1.ToString() + ((Vector3)value).x + Spriter1.ToString() + ((Vector3)value).y + Spriter1.ToString() + ((Vector3)value).z + BBracket1.ToString());
            }
            if (type == typeof(Vector2))
            {
                return(FBracket1.ToString() + ((Vector2)value).x + Spriter1.ToString() + ((Vector2)value).y + BBracket1.ToString());
            }
            if (type == typeof(Vector4))
            {
                return(FBracket1.ToString() + ((Vector4)value).x + Spriter1.ToString() + ((Vector4)value).y + Spriter1.ToString() + ((Vector4)value).z + Spriter1.ToString() + ((Vector4)value).w + BBracket1.ToString());
            }
            if (type == typeof(Quaternion))
            {
                return(FBracket1.ToString() + ((Quaternion)value).x + Spriter1.ToString() + ((Quaternion)value).y + Spriter1.ToString() + ((Quaternion)value).z + Spriter1.ToString() + ((Quaternion)value).w + BBracket1.ToString());
            }
            if (type == typeof(Color))
            {
                return(FBracket1.ToString() + ((Color)value).r + Spriter1.ToString() + ((Color)value).g + Spriter1.ToString() + ((Color)value).b + BBracket1.ToString());
            }
            if (type.BaseType == typeof(Enum))
            {
                return(Enum.GetName(type, value));
            }
            if (type.IsGenericType && (type.GetGenericTypeDefinition() == typeof(Dictionary <,>)))
            {
                int Count = (int)type.GetProperty("Count").GetValue(value, null);
                if (Count == 0)
                {
                    return(String.Empty);
                }
                MethodInfo   getIe            = type.GetMethod("GetEnumerator");
                object       enumerator       = getIe.Invoke(value, new object[0]);
                System.Type  enumeratorType   = enumerator.GetType();
                MethodInfo   moveToNextMethod = enumeratorType.GetMethod("MoveNext");
                PropertyInfo current          = enumeratorType.GetProperty("Current");

                StringBuilder stringBuilder = new StringBuilder();

                while (enumerator != null && (bool)moveToNextMethod.Invoke(enumerator, new object[0]))
                {
                    stringBuilder.Append(Spriter1.ToString() + ConverToString(current.GetValue(enumerator, null)));
                }

                return(stringBuilder.ToString().ReplaceFirst(Spriter1.ToString(), ""));
            }
            if (type.IsGenericType && (type.GetGenericTypeDefinition() == typeof(KeyValuePair <,>)))
            {
                object pairKey   = type.GetProperty("Key").GetValue(value, null);
                object pairValue = type.GetProperty("Value").GetValue(value, null);

                string keyStr   = ConverToString(pairKey);
                string valueStr = ConverToString(pairValue);
                return(keyStr + Spriter2.ToString() + valueStr);
            }
            if (type.IsGenericType && (type.GetGenericTypeDefinition() == typeof(List <>)))
            {
                int Count = (int)type.GetProperty("Count").GetValue(value, null);
                if (Count == 0)
                {
                    return(String.Empty);
                }
                MethodInfo mget = type.GetMethod("get_Item", BindingFlags.Instance | BindingFlags.Public);

                StringBuilder stringBuilder = new StringBuilder();

                object item;
                string itemStr;

                for (int i = 0; i < Count - 1; i++)
                {
                    item    = mget.Invoke(value, new object[] { i });
                    itemStr = StringEx.ConverToString(item);
                    stringBuilder.Append(itemStr + Spriter1.ToString());
                }
                item    = mget.Invoke(value, new object[] { Count - 1 });
                itemStr = StringEx.ConverToString(item);
                stringBuilder.Append(itemStr);

                return(stringBuilder.ToString());
            }
            if (type == typeof(ArrayList))
            {
                StringBuilder builder   = new StringBuilder();
                var           arrayList = value as ArrayList;
                for (int i = 0; i < arrayList.Count - 1; i++)
                {
                    builder.Append(arrayList[i].ConverToString()).Append(",");
                }
                builder.Append(arrayList[arrayList.Count - 1].ConverToString());
                return(builder.ToString());
            }
            if (type == typeof(Hashtable))
            {
                StringBuilder builder = new StringBuilder();
                var           table   = value as Hashtable;
                IEnumerator   e       = table.Keys.GetEnumerator();
                while (e.MoveNext())
                {
                    var tableKey   = e.Current.ConverToString();
                    var tableValue = table[e.Current].ConverToString();
                    builder.Append(tableKey).Append(StringEx.Spriter2).Append(tableValue).Append(StringEx.Spriter1);
                }
                builder.Remove(builder.Length - 2, 1);
                return(builder.ToString());
            }
            if (type.IsArray)
            {
                StringBuilder stringBuilder = new StringBuilder();
                var           array         = value as Array;
                if (array.Length > 0)
                {
                    stringBuilder.Append(ConverToString(array.GetValue(0)));
                    for (int i = 1; i < array.Length; i++)
                    {
                        stringBuilder.Append(Spriter1.ToString());
                        stringBuilder.Append(ConverToString(array.GetValue(i)));
                    }
                    return(stringBuilder.ToString());
                }
                else
                {
                    return(string.Empty);
                }
            }
            if (CanConvertToString(type))
            {
                return(ToStringableObjectConvertToString(value, type));
            }
            return(value.ToString());
        }
Ejemplo n.º 48
0
    /// <summary>
    /// 将值转化成指定类型
    /// </summary>
    /// <param name="obj"></param>
    /// <param name="type"></param>
    /// <returns></returns>
    public static object GetValue(object obj, System.Type type, string propertyName)
    {
        string value = obj.ToString().Trim();

        if (string.IsNullOrEmpty(value))
        {
            if (type == typeof(int) || type == typeof(float) || type == typeof(double) ||
                type == typeof(uint) || type == typeof(byte) || type == typeof(sbyte) ||
                type == typeof(short) || type == typeof(long) || type == typeof(Int32) ||
                type == typeof(Int64))
            {
                return(0);
            }
            if (type == typeof(bool))
            {
                return(false);
            }
        }
        if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(List <>))
        {
            string[] tempArry   = value.Split('|', ';', ':', ',');
            var      memberType = type.GetGenericArguments()[0];
            var      listType   = typeof(List <>).MakeGenericType(new Type[] { memberType });
            var      list       = Activator.CreateInstance(listType, new object[] { });

            //List<string> tempList = new List<string>();
            for (int i = 0; i < tempArry.Length; i++)
            {
                object addItem = GetValue(tempArry[i], memberType, "");
                list.GetType().InvokeMember("Add", BindingFlags.Default | BindingFlags.InvokeMethod, null, list, new object[] { addItem });
                //tempList.Add(tempArry[i]);
            }
            //return tempList;
            return(list);
        }
        if (type == typeof(bool))
        {
            float temp = float.Parse(value);
            if (temp != 0)
            {
                return(true);
            }
            return(false);
        }
        else if (type.BaseType == typeof(Enum))
        {
            return(GetValue(value, Enum.GetUnderlyingType(type), ""));
        }
        if (type == typeof(Vector3))
        {
            string[] tempArry = value.Split('|', ';', ':', ',');
            Vector3  temp;
            if (tempArry.Length < 3)
            {
                temp = Vector3.zero;
            }
            else
            {
                temp = new Vector3(float.Parse(tempArry[0]), float.Parse(tempArry[1]), float.Parse(tempArry[2]));
            }
            return(temp);
        }
        if (type == typeof(Vector2))
        {
            string[] tempArry = value.Split('|', ';', ':', ',');
            Vector2  temp;
            if (tempArry.Length < 2)
            {
                temp = Vector2.zero;
            }
            else
            {
                temp = new Vector2(float.Parse(tempArry[0]), float.Parse(tempArry[1]));
            }
            return(temp);
        }
        return(System.Convert.ChangeType(value, type));
    }
Ejemplo n.º 49
0
        private static object changeType(System.Type t, object value)
        {
            object result;

            if ((t == typeof(bool) || t == typeof(bool?)) && value != null && value.GetType() == typeof(string))
            {
                string stringValue = (string)value;
                string text        = stringValue.ToUpper();
                switch (text)
                {
                case "T":
                    result = true;
                    return(result);

                case "F":
                    result = false;
                    return(result);

                case "Y":
                    result = true;
                    return(result);

                case "N":
                    result = false;
                    return(result);

                case "YES":
                    result = true;
                    return(result);

                case "NO":
                    result = false;
                    return(result);

                case "1":
                    result = true;
                    return(result);

                case "0":
                    result = false;
                    return(result);
                }
            }

            if (t.IsGenericType && t.GetGenericTypeDefinition() == typeof(System.Nullable <>))
            {
                if (value == null)
                {
                    result = null;
                }
                else
                {
                    result = System.Convert.ChangeType(value, System.Nullable.GetUnderlyingType(t));
                }
            }
            else
            {
                result = System.Convert.ChangeType(value, t);
            }

            return(result);
        }
Ejemplo n.º 50
0
 public static bool IsNullableType(System.Type colType)
 {
     return((colType.IsGenericType) &&
            (colType.GetGenericTypeDefinition() == typeof(System.Nullable <>)));
 }
Ejemplo n.º 51
0
    static object GetValue(System.Type fieldType, object data)
    {
        object value = null;

        // Generics
        if (fieldType.IsGenericType)
        {
            //List<>
            if (fieldType.GetGenericTypeDefinition() == typeof(List <>))
            {
                if (data is IList)
                {
                    // Create list
                    IList newList = System.Activator.CreateInstance(fieldType) as IList;
                    // If we are a list of Classes, 2d array/list, not primitive types
                    System.Type listItemType = fieldType.GetGenericArguments()[0];
                    bool        isClassType  = listItemType.IsClass && listItemType != typeof(string);
                    bool        isGeneric    = listItemType.IsGenericType;
                    bool        isArray      = listItemType.IsArray;
                    // Add from list
                    foreach (object listValue in (data as IList))
                    {
                        object v = null;
                        if (isClassType || isGeneric || isArray)
                        {
                            v = GetValue(listItemType, listValue);
                        }
                        else
                        {
                            v = ChangeType(listValue, listItemType);
                        }
                        newList.Add(v);
                    }
                    value = newList;
                }
                else
                {
                    Debug.LogError("Incorrect data format for a List<>. {0} but should be IList" + data.GetType().Name);
                }
            }
            else
            {
                Debug.LogError("No support to read in the type " + fieldType.Name);
            }
            // No support for any other generics yet
        }
        // Array
        else if (fieldType.IsArray)
        {
            if (data is IList)
            {
                // Create array
                System.Array array = System.Array.CreateInstance(fieldType.GetElementType(), (data as IList).Count);
                // If we are a list of Classes, 2d array/list, not primitive types
                System.Type arrayItemType = fieldType.GetElementType();
                bool        isClassType   = arrayItemType.IsClass && arrayItemType != typeof(string);
                bool        isGeneric     = arrayItemType.IsGenericType;
                bool        isArray       = arrayItemType.IsArray;
                // Add from list
                int i = 0;
                foreach (object listValue in (data as IList))
                {
                    object v = null;
                    if (isClassType || isGeneric || isArray)
                    {
                        v = GetValue(arrayItemType, listValue);
                    }
                    else
                    {
                        v = ChangeType(listValue, arrayItemType);
                    }
                    array.SetValue(v, i++);
                }
                value = array;
            }
            else
            {
                value = null; // Empty arrays are now set to null
                              //Debug.LogError("Incorrect data format for an array. {0} but should be IList" + data.GetType().Name);
            }
        }
        // Object field
        else if (fieldType.IsClass && fieldType != typeof(string))
        {
            Dictionary <string, object> objectData = data as Dictionary <string, object>;
            if (objectData != null)
            {
                value = System.Activator.CreateInstance(fieldType);
                ApplyData(value, objectData, "", "");
            }
            else
            {
                Debug.LogError("Incorrect data format for a class. {0} but should be Dictionary<string, object>" + data.GetType().Name);
            }
        }
        else if (fieldType == typeof(DateTime))
        {
            if (data != null)
            {
                string strData = (string)data;
                if (strData.Equals(""))        //If it's null it's an error, if it's empty means default value.
                {
                    value = DateTime.MinValue; //If field was left empty on DB, use a default value.
                }
                else if (strData != null)
                {
                    value = (object)SaveUtilities.ParseDateTime(strData, DateTime.Now, "GameData.GetValue: ");
                }
                else
                {
                    Debug.LogError("Incorrect data format for a Date. {0} but should be a valid DateTime using format DD/MM/YYYY hh:mm:ss" + data.GetType().Name);
                }
            }
            else
            {
                Debug.LogError("Incorrect data format for a Date. {0} but should be a valid DateTime using format DD/MM/YYYY hh:mm:ss" + data.GetType().Name);
            }
        }
        // Individual field
        else
        {
            try
            {
                System.Type valueType = data.GetType();
                if (fieldType.IsEnum && (valueType == typeof(int) || valueType == typeof(long)))
                {
                    value = System.Enum.ToObject(fieldType, data);
                }
                else
                {
                    value = ChangeType(data, fieldType);
                    if (fieldType.IsEnum)
                    {
                        if (value == null)
                        {
                            Debug.LogError(string.Format("Unable to convert {0} to type {1}", data, fieldType));
                        }
                    }
                }
            }
            catch (System.Exception e)
            {
                Debug.LogError(e.Message);
                Debug.LogError(string.Format("Unable to convert {0} to type {1}", data.GetType(), fieldType));
            }
        }
        return(value);
    }
Ejemplo n.º 52
0
 private static bool IsIList(System.Type propType)
 {
     return(typeof(System.Collections.Generic.IList <>) == propType.GetGenericTypeDefinition() || typeof(System.Collections.Generic.List <>) == propType.GetGenericTypeDefinition());
 }
Ejemplo n.º 53
0
 public static bool isList(System.Type t)
 {
     return(t.IsGenericType && t.GetGenericTypeDefinition() == typeof(List <>));
 }
Ejemplo n.º 54
0
 private static bool IsNullableOfT(System.Type type)
 {
     return(type.IsGenericType &&
            type.GetGenericTypeDefinition().Equals(typeof(Nullable <>)));
 }
Ejemplo n.º 55
0
 internal static bool IsArrayOrList(this System.Type listType)
 {
     return(listType.IsArray || (listType.IsGenericType && (listType.GetGenericTypeDefinition() == typeof(List <>))));
 }
Ejemplo n.º 56
0
 public static bool IsNullable(this System.Type type)
 {
     return(type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable <>));
 }
Ejemplo n.º 57
0
        public static bool InheritsFrom(this System.Type type, System.Type baseType)
        {
            if (baseType.IsAssignableFrom(type))
            {
                return(true);
            }
            if (type.IsInterface && !baseType.IsInterface)
            {
                return(false);
            }
            if (baseType.IsInterface)
            {
                return(Enumerable.Contains(type.GetInterfaces(), baseType));
            }
            for (System.Type currentType = type; currentType != null; currentType = currentType.BaseType)
            {
                if (currentType == baseType || baseType.IsGenericTypeDefinition && currentType.IsGenericType && currentType.GetGenericTypeDefinition() == baseType)
                {
                    return(true);
                }
            }

            return(false);
        }
 private static System.Type GetMemberTypeOrGenericCollectionType(MemberInfo member)
 {
     System.Type type = GetMemberType(member);
     return(type.IsGenericType ? type.GetGenericTypeDefinition() : type);
 }
Ejemplo n.º 59
0
 private static bool InheritsFrom(System.Type type, System.Type baseType)
 {
     if (baseType.IsAssignableFrom(type))
     {
         return(true);
     }
     if (type.IsInterface && !baseType.IsInterface)
     {
         return(false);
     }
     if (baseType.IsInterface)
     {
         return(((IEnumerable <System.Type>)type.GetInterfaces()).Contains <System.Type>(baseType));
     }
     for (System.Type type1 = type; type1 != null; type1 = type1.BaseType)
     {
         if (type1 == baseType || baseType.IsGenericTypeDefinition && type1.IsGenericType && type1.GetGenericTypeDefinition() == baseType)
         {
             return(true);
         }
     }
     return(false);
 }
Ejemplo n.º 60
0
        private static object CreateInstance(BuildXLContext context, Type type, bool booleanDefault)
        {
            string path = A("x", "path");

            type = GetNonNullableType(type);

            if (type == typeof(bool))
            {
                return(booleanDefault);
            }

            if (type == typeof(double))
            {
                return((double)0.23423);
            }

            if (type == typeof(byte))
            {
                return((byte)123);
            }

            if (type == typeof(sbyte))
            {
                return((sbyte)123);
            }

            if (type == typeof(short))
            {
                return((short)123);
            }

            if (type == typeof(ushort))
            {
                return((ushort)123);
            }

            if (type == typeof(int))
            {
                return(123);
            }

            if (type == typeof(uint))
            {
                return((uint)123);
            }

            if (type == typeof(long))
            {
                return((long)123);
            }

            if (type == typeof(ulong))
            {
                return((ulong)123);
            }

            if (type == typeof(string))
            {
                return("nonDefaultString");
            }

            if (type == typeof(ModuleId))
            {
                return(ModuleId.UnsafeCreate(123));
            }

            if (type == typeof(LocationData))
            {
                return(new LocationData(AbsolutePath.Create(context.PathTable, path), 12, 23));
            }

            if (type == typeof(AbsolutePath))
            {
                return(AbsolutePath.Create(context.PathTable, path));
            }

            if (type == typeof(RelativePath))
            {
                string relativePath = R("rel1", "dir1", "path");
                return(RelativePath.Create(context.StringTable, relativePath));
            }

            if (type == typeof(FileArtifact))
            {
                return(FileArtifact.CreateSourceFile(AbsolutePath.Create(context.PathTable, path)));
            }

            if (type == typeof(PathAtom))
            {
                return(PathAtom.Create(context.StringTable, "atom"));
            }

            if (type == typeof(global::BuildXL.Utilities.LineInfo))
            {
                return(new global::BuildXL.Utilities.LineInfo(1, 1));
            }

            if (type.GetTypeInfo().IsEnum)
            {
                bool first = true;
                foreach (var value in Enum.GetValues(type))
                {
                    if (!first)
                    {
                        return(value);
                    }

                    first = false;
                }

                XAssert.Fail($"Enum {type.FullName} doesn't have more than one value, so can't pick the second one.");
            }

            if (type.GetTypeInfo().IsGenericType)
            {
                var generic = type.GetGenericTypeDefinition();

                if (generic == typeof(IReadOnlyList <>))
                {
                    // Treat IReadOnlyList as if it was List
                    type    = typeof(List <>).MakeGenericType(type.GenericTypeArguments[0]);
                    generic = type.GetGenericTypeDefinition();
                }

                if (generic == typeof(List <>))
                {
                    var newList = (IList)Activator.CreateInstance(type);
                    newList.Add(CreateInstance(context, type.GenericTypeArguments[0], booleanDefault));
                    return(newList);
                }

                if (generic == typeof(IReadOnlyDictionary <,>))
                {
                    // Treat IReadOnlyList as if it was List
                    type    = typeof(Dictionary <,>).MakeGenericType(type.GenericTypeArguments[0], type.GenericTypeArguments[1]);
                    generic = type.GetGenericTypeDefinition();
                }

                if (generic == typeof(Dictionary <,>))
                {
                    var newDictionary = (IDictionary)Activator.CreateInstance(type);
                    newDictionary.Add(
                        CreateInstance(context, type.GenericTypeArguments[0], booleanDefault),
                        CreateInstance(context, type.GenericTypeArguments[1], booleanDefault));
                    return(newDictionary);
                }

                if (generic == typeof(ValueTuple <,>))
                {
                    var newTuple = Activator.CreateInstance(type);

                    // In ValueTuple classes, the first 7 values are accessible via Item1-Item7 fields.
                    // The tuple field names (named tuples) aren't part of runtime representation.
                    type.GetField("Item1").SetValue(newTuple, CreateInstance(context, type.GenericTypeArguments[0], booleanDefault));
                    type.GetField("Item2").SetValue(newTuple, CreateInstance(context, type.GenericTypeArguments[1], booleanDefault));

                    return(newTuple);
                }
            }

            if (type.GetTypeInfo().IsInterface)
            {
                // Treat interfaces as if it was the mutable class
                type = ConfigurationConverter.FindImplementationType(
                    type,
                    ObjectLiteral.Create(new List <Binding>(), default(LineInfo), AbsolutePath.Invalid),

                    // Return a SourceResolver to instantiate
                    () => "SourceResolver");
            }

            if (type.GetTypeInfo().IsClass)
            {
                var instance = Activator.CreateInstance(type);
                PopulateObject(context, type, instance, booleanDefault);
                return(instance);
            }

            XAssert.Fail($"Don't know how to create objects for this type: {type.FullName}.");
            return(null);
        }