コード例 #1
0
        /// <summary>
        /// Create a new instance from a Type
        /// </summary>
        public static object CreateInstance(Type type)
        {
            try
            {
                if (_cacheCtor.TryGetValue(type, out var c))
                {
                    return(c());
                }
            }
            catch (Exception ex)
            {
                throw LiteException.InvalidCtor(type, ex);
            }

            lock (_cacheCtor)
            {
                try
                {
                    if (_cacheCtor.TryGetValue(type, out var c))
                    {
                        return(c());
                    }

                    if (TypeInfoExtensions.GetTypeInfo(type).IsClass)
                    {
                        _cacheCtor.Add(type, c = CreateClass(type));
                    }
                    else if (TypeInfoExtensions.GetTypeInfo(type).IsInterface) // some know interfaces
                    {
                        if (TypeInfoExtensions.GetTypeInfo(type).IsGenericType)
                        {
                            var typeDef = type.GetGenericTypeDefinition();

                            if (typeDef == typeof(IList <>) ||
                                typeDef == typeof(ICollection <>) ||
                                typeDef == typeof(IEnumerable <>))
                            {
                                return(CreateInstance(GetGenericListOfType(UnderlyingTypeOf(type))));
                            }
                            else if (typeDef == typeof(IDictionary <,>))
                            {
                                var k = TypeInfoExtensions.GetTypeInfo(type).GetGenericArguments()[0];
                                var v = TypeInfoExtensions.GetTypeInfo(type).GetGenericArguments()[1];

                                return(CreateInstance(GetGenericDictionaryOfType(k, v)));
                            }
                        }

                        throw LiteException.InvalidCtor(type, null);
                    }
                    else // structs
                    {
                        _cacheCtor.Add(type, c = CreateStruct(type));
                    }

                    return(c());
                }
                catch (Exception ex)
                {
                    throw LiteException.InvalidCtor(type, ex);
                }
            }
        }