CreateInstance() public static method

public static CreateInstance ( Type rType, BindingFlags, rBindFlags ) : object
rType Type
rBindFlags BindingFlags,
return object
Exemplo n.º 1
0
        static Logger()
        {
            LoggerImplementDict.Add("Console", typeof(ConsoleLogImpl));
            LoggerImplementDict.Add("File", typeof(FileLogImpl));

            LogSetting.Default.Level = LogLevel.Core;
            if (LogSetting.Default.Target == null)
            {
                LogSetting.Default.Target = new List <string>();
                LogSetting.Default.Target.Add("File");
            }

            if (LogSetting.Default.Level == null)
            {
                LogSetting.Default.Level = LogLevel.Error;
            }

            foreach (string targetItem in LogSetting.Default.Target)
            {
                ILogImpl logImpl =
                    ReflectionUtil.CreateInstance(LoggerImplementDict[targetItem])
                    as ILogImpl;

                if (logImpl != null)
                {
                    Init(logImpl);
                }
            }
        }
 public bool Read()
 {
     while (this._reader2.Read())
     {
         if ((this._reader2.NodeType == XmlNodeType.Element) && (this._reader2.Name == "item"))
         {
             string attribute    = this._reader2.GetAttribute("key");
             string assemblyName = this._reader2.GetAttribute("assembly");
             string typeName     = this._reader2.GetAttribute("type");
             string name         = this._reader2.GetAttribute("lang");
             if (typeName == null)
             {
                 string str2 = this._reader2.IsEmptyElement ? string.Empty : this._reader2.ReadString();
                 this._current = new Info(attribute, str2, (name == null) ? this._globalCulture : new CultureInfo(name), false);
             }
             else
             {
                 object obj2 = ReflectionUtil.CreateInstance(assemblyName, typeName);
                 if (!(obj2 is IInfoItem))
                 {
                     throw new NotSupportedException("invaild item object");
                 }
                 ((IInfoItem)obj2).ReadXml(this._reader);
                 this._current = new Info(attribute, obj2, (name == null) ? this._globalCulture : new CultureInfo(name), true);
             }
             return(true);
         }
     }
     return(false);
 }
Exemplo n.º 3
0
 public static object DynamicToObject(dynamic src, Type dtype)
 {
     try
     {
         if (dtype.IsPrimitive || dtype == (typeof(string)))
         {
             return(Convert.ChangeType(src, dtype));
         }
         else if (dtype.IsEnum)
         {
             return(Enum.Parse(dtype, src.ToString()));
         }
         else if (dtype.IsArray)
         {
             ArrayList temp        = new ArrayList();
             var       elementType = dtype.GetElementType();
             foreach (dynamic sitem in src)
             {
                 var ditem = DynamicToObject(sitem, elementType);
                 temp.Add(ditem);
             }
             Array dfv = ReflectionUtil.CreateInstance(dtype, temp.Count) as Array;
             for (int i = 0; i < temp.Count; i++)
             {
                 dfv.SetValue(temp[i], i);
             }
             return(dfv);
         }
         else if (dtype.GetInterface(typeof(IList).Name) != null)
         {
             var dfv         = ReflectionUtil.CreateInstance(dtype) as IList;
             var elementType = dtype.GetGenericArguments()[0];
             foreach (dynamic sitem in src)
             {
                 var ditem = DynamicToObject(sitem, elementType);
                 dfv.Add(ditem);
             }
             return(dfv);
         }
         else
         {
             var dst = ReflectionUtil.CreateInstance(dtype);
             foreach (var f in dtype.GetFields())
             {
                 dynamic sfv = src[f.Name];
                 if (sfv != null)
                 {
                     var ditem = DynamicToObject(sfv, f.FieldType);
                     f.SetValue(dst, ditem);
                 }
             }
             return(dst);
         }
     }
     catch (Exception err)
     {
         Console.WriteLine(err.Message);
         return(null);
     }
 }
Exemplo n.º 4
0
        private DbDriver GetDbDriver(string connectionName,
                                     string providerName, string connectionString)
        {
            DbDriver driver     = null;
            string   driverName = string.Empty;

            DataRow[] rows = providerTable.Select(string.Format("invariantname='{0}'", providerName));

            DbProviderFactory dbProviderFactory = null;

            if (rows != null && rows.Length > 0)
            {
                dbProviderFactory = DbProviderFactories.GetFactory(rows[0]);
            }
            else
            {
                if (string.Compare(providerName, "System.Data.SQLite", true) == 0)
                {
                    dbProviderFactory = ReflectionUtil.CreateInstance("System.Data.SQLite.SQLiteFactory, System.Data.SQLite") as DbProviderFactory;
                }
                else if (string.Compare(providerName, "Npgsql", true) == 0)
                {
                    dbProviderFactory = ReflectionUtil.CreateInstance("Npgsql.NpgsqlFactory, Npgsql") as DbProviderFactory;
                }
            }

            ThrowExceptionUtil.ArgumentConditionTrue(dbProviderFactory != null, "connectionKey",
                                                     "the providerName of the connection setting '{0}' error, please check it.".FormatWith(connectionName));

            string[] keyArray = connectionName.Split("#".ToCharArray());
            if (keyArray.Length == 2)
            {
                string key = keyArray[0];
                driverName = keyArray[1];

                driver = ReflectionUtil.CreateInstance(driverNameDict[string.Format(DriverClassNameTemplate, driverName)],
                                                       dbProviderFactory, connectionString, connectionName) as DbDriver;
            }

            if (driver == null)
            {
                foreach (string key in ruleDict.Keys)
                {
                    if (providerName.IndexOf(key, StringComparison.CurrentCultureIgnoreCase) >= 0)
                    {
                        driverName = ruleDict[key];
                        break;
                    }
                }

                driver = ReflectionUtil.CreateInstance(driverNameDict[string.Format(DriverClassNameTemplate, driverName)],
                                                       dbProviderFactory, connectionString, connectionName) as DbDriver;
            }

            ThrowExceptionUtil.ArgumentConditionTrue(driver != null, "connectionName",
                                                     "the connection setting '{0}' error, please check it.".FormatWith(connectionName));

            return(driver);
        }
Exemplo n.º 5
0
            /// <summary>
            /// Creates an instance of a specific type.
            /// </summary>
            /// <param name="type">The type of the instance to create.</param>
            private static object CreateInstance(Type type)
            {
                if (services.ContainsKey(type))
                {
                    return(services[type].ServiceImplementation);
                }

                return(ReflectionUtil.CreateInstance(type));
            }
Exemplo n.º 6
0
        public static object CreateInstance(string typeFullName, BindingFlags bindingAttr = BindingFlags.CreateInstance, object[] args = null)
        {
            if (string.IsNullOrEmpty(typeFullName))
            {
                throw new ArgumentNullException("typeFullName");
            }

            Type type = ProjectAssemblies.GetType(typeFullName);

            return(ReflectionUtil.CreateInstance(type, bindingAttr, args));
        }
Exemplo n.º 7
0
        /// <summary>
        /// Creates the Type parser.
        /// </summary>
        /// <param name="typeKeyword">The Type keyword.</param>
        /// <returns>The Type parser.</returns>
        public static ITypeParser CreateTypeParser(string typeKeyword)
        {
            Type type = GetTypeParserType(typeKeyword);

            if (type != null)
            {
                return((ITypeParser)ReflectionUtil.CreateInstance(type));
            }

            return(null);
        }
Exemplo n.º 8
0
        /// <summary>
        /// 弹出窗体
        /// </summary>
        /// <param name="type">待显示的窗体类型</param>
        public static void PopDialogForm(Type type)
        {
            object form = ReflectionUtil.CreateInstance(type);

            if ((typeof(Form)).IsAssignableFrom(form.GetType()))
            {
                Form tmp = form as Form;
                tmp.ShowInTaskbar = false;
                tmp.StartPosition = FormStartPosition.CenterScreen;
                tmp.ShowDialog();
            }
        }
Exemplo n.º 9
0
        public object GetConfig(string section, string key)
        {
            string str2;
            string str3;

            if (section == null)
            {
                throw new ArgumentNullException("section");
            }
            if (key == null)
            {
                throw new ArgumentNullException("key");
            }
            ReflectionUtil.ParseTypeName(this.GetString(section, key), out str3, out str2);
            return(ReflectionUtil.CreateInstance(str3, str2));
        }
Exemplo n.º 10
0
        protected virtual bool ReadItem(XmlReader reader)
        {
            object obj3;
            object attribute    = reader.GetAttribute("key");
            string typeName     = reader.GetAttribute("type");
            string assemblyName = reader.GetAttribute("assembly");

            if (Convert.ToBoolean(reader.GetAttribute("iswraped")))
            {
                obj3 = ReflectionUtil.CreateInstance(assemblyName, typeName);
                object objectWarp = this.GetObjectWarp(obj3);
                if (!(objectWarp is IObjectXmlSerializable))
                {
                    throw new InvalidCastException("cann't found wraped object");
                }
                ((IObjectXmlSerializable)objectWarp).Wrap(obj3);
                ((IObjectXmlSerializable)objectWarp).ReadXml(reader);
                this.ptable[attribute] = ((IObjectXmlSerializable)objectWarp).UnWrap();
                if ((reader.NodeType == XmlNodeType.EndElement) && (reader.Name == "objectTable"))
                {
                    return(false);
                }
                if (((reader.NodeType == XmlNodeType.Element) && (reader.Name == "item")) && !attribute.Equals(reader.GetAttribute("key")))
                {
                    return(this.ReadItem(reader));
                }
                return(true);
            }
            if (reader.IsEmptyElement)
            {
                this.ptable[attribute] = null;
            }
            else
            {
                if (typeName == null)
                {
                    obj3 = reader.IsEmptyElement ? string.Empty : reader.ReadString();
                }
                else
                {
                    obj3 = Convert.ChangeType(reader.IsEmptyElement ? string.Empty : reader.ReadString(), ReflectionUtil.GetType(assemblyName, typeName));
                }
                this.ptable[attribute] = obj3;
            }
            return(true);
        }
Exemplo n.º 11
0
        /// <summary>
        /// 把控件附加到窗体上弹出
        /// </summary>
        /// <param name="control">待显示的控件</param>
        /// <param name="caption">窗体显示的标题</param>
        public static void PopControlForm(Type control, string caption)
        {
            object ctr = ReflectionUtil.CreateInstance(control);

            if ((typeof(Control)).IsAssignableFrom(ctr.GetType()))
            {
                Form tmp = new Form();
                tmp.WindowState   = FormWindowState.Maximized;
                tmp.ShowIcon      = false;
                tmp.Text          = caption;
                tmp.ShowInTaskbar = false;
                tmp.StartPosition = FormStartPosition.CenterScreen;
                Control ctrtmp = ctr as Control;
                ctrtmp.Dock = DockStyle.Fill;
                tmp.Controls.Add(ctrtmp);
                tmp.ShowDialog();
            }
        }
Exemplo n.º 12
0
        private void on_do_1s(ZoneLayer layer)
        {
            layer.AddTimeDelayMS(bot.Random.Next(1000, 10000), (t) =>
            {
                if (Enable)
                {
                    client.GameSocket.playerHandler.battleEventNotify(null);
                    client.GameSocket.rankHandler.getRankInfoRequest((err, rsp) => { });
                }
            });

            {
                var req_type = CUtils.GetRandomInArray <Type>(all_request, bot.Random);
                var req      = ReflectionUtil.CreateInstance(req_type);
                fill_random(req);
                log.Info("request : " + req_type);
                bot.Client.GameSocket.request(req, (err, rsp) =>
                {
                    log.Info("response : rsp=" + rsp + " : err=" + err);
                });
            }
            {
                var ntf_type = CUtils.GetRandomInArray <Type>(all_notify, bot.Random);
                var ntf      = ReflectionUtil.CreateInstance(ntf_type);
                fill_random(ntf);
                log.Info("notify : " + ntf_type);
                bot.Client.GameSocket.notify(ntf);
            }
            {
                var battleMessage = random_bytes();
                client.GameSocket.playerHandler.battleEventNotify(battleMessage);
            }
            {
                var req_type = CUtils.GetRandomInArray <Type>(all_request, bot.Random);
                socket_start_send(EventTypes.GetRequestKey(req_type), (uint)bot.Random.Next());
            }
            {
                var ntf_type = CUtils.GetRandomInArray <Type>(all_notify, bot.Random);
                socket_start_send(EventTypes.GetNotifyKey(ntf_type));
            }
        }
Exemplo n.º 13
0
        protected object CreateInstanceCore(ConstructorCandidate constructor, object[] arguments, Type implType)
        {
            object instance;

            try
            {
                object instance1;
#if (SILVERLIGHT)
                instance = ReflectionUtil.CreateInstance <object>(implType, arguments);
#else
                if (useFastCreateInstance)
                {
                    instance1 = FastCreateInstance(implType, arguments, constructor);
                }
                else
                {
                    instance1 = implType.CreateInstance <object>(arguments);
                }
#endif
                instance = instance1;
            }
            catch (Exception ex)
            {
                if (arguments != null)
                {
                    foreach (var argument in arguments)
                    {
                        Kernel.ReleaseComponent(argument);
                    }
                }

                throw new ComponentActivatorException(
                          "ComponentActivator: could not instantiate " + Model.Implementation.FullName, ex);
            }
            return(instance);
        }
Exemplo n.º 14
0
        /// <summary>
        /// Parses the specified string in an object of the specified type
        /// </summary>
        /// <param name="reader">The input reader</param>
        /// <param name="t">The type of the object that needs to be parsed</param>
        /// <returns>The parsed object</returns>
        public object Parse(TextReader reader, Type t)
        {
            object ret = null;

            List <KeyValuePair <string, string> > singleValues = new List <KeyValuePair <string, string> >();
            Dictionary <string, List <List <KeyValuePair <string, string> > > > arrayValues =
                new Dictionary <string, List <List <KeyValuePair <string, string> > > >();
            List <List <KeyValuePair <string, string> > > curArrayList;

            // parse properties into single keyvalue pairs and the indexed properties into
            // the array Values
            #region Parse properties
            string curLine = reader.ReadLine();
            int    idxSeparator, idxIndex1, idxIndex2;
            string key, val, keyIndex, keyIndexBase, keyIndexProp;
            int    curIndex;
            while (curLine != null)
            {
                curLine = curLine.Trim();
                if (!string.IsNullOrEmpty(curLine) && curLine[0] != COMMENT_CHAR)
                {
                    idxSeparator = curLine.IndexOf(SEPARATOR_CHAR);
                    if (idxSeparator != -1)
                    {
                        key = curLine.Substring(0, idxSeparator);
                        val = curLine.Substring(idxSeparator + 1);

                        // check if the key is indexed/array
                        idxIndex1 = key.IndexOf(INDEX_START_CHAR);
                        if (idxIndex1 == -1)
                        {
                            singleValues.Add(new KeyValuePair <string, string>(key, val));
                        }
                        else
                        {
                            idxIndex2 = key.IndexOf(INDEX_END_CHAR);
                            if (idxIndex2 < idxIndex1)
                            {
                                throw new InvalidDataException("Cannot read index for property: " + key);
                            }
                            else
                            {
                                keyIndex = key.Substring(idxIndex1 + 1, idxIndex2 - idxIndex1 - 1);
                                if (int.TryParse(keyIndex, out curIndex))
                                {
                                    keyIndexBase = key.Substring(0, idxIndex1);
                                    keyIndexProp = key.Substring(idxIndex2 + 2);

                                    if (!arrayValues.ContainsKey(keyIndexBase))
                                    {
                                        arrayValues[keyIndexBase] = new List <List <KeyValuePair <string, string> > >();
                                    }
                                    curArrayList = arrayValues[keyIndexBase];
                                    if (curArrayList == null || curArrayList.Count <= curIndex)
                                    {
                                        curArrayList.Add(new List <KeyValuePair <string, string> >());
                                    }
                                    curArrayList[curIndex].Add(new KeyValuePair <string, string>(keyIndexProp, val));
                                }
                                else
                                {
                                    throw new InvalidDataException("Not a valid indexed property: " + key);
                                }
                            }
                        }
                    }
                }
                curLine = reader.ReadLine();
            }
            #endregion

            // create a new object for type
            ret = ReflectionUtil.CreateInstance(t);

            ReflectionCache typeCache   = ReflectionUtil.GetCache(t);
            PropertyInfo    piSpecified = null;

            // now reflect through the specified type and set parsed values
            foreach (KeyValuePair <string, string> kvp in singleValues)
            {
                ReflectionUtil.SetPropertyPathValue(ret, kvp.Key, kvp.Value);

                // also set the "Specified"-flag, if any
                piSpecified = typeCache.GetProperty(kvp.Key + "Specified", false);
                if (piSpecified != null)
                {
                    piSpecified.SetValue(ret, true, null);
                }
            }

            object curRootObject;
            List <KeyValuePair <string, string> > curRootObjectProperties;
            PropertyInfo    pi;
            ConstructorInfo ci;

            foreach (string arrayPropertyName in arrayValues.Keys)
            {
                curArrayList = arrayValues[arrayPropertyName];

                pi = ReflectionUtil.GetProperty(t, arrayPropertyName);
                ci = pi.PropertyType.GetConstructor(new Type[] { typeof(int) });
                object[] o = (object[])ci.Invoke(new object[] { curArrayList.Count });

                Type elementType = pi.PropertyType.Assembly.GetType(pi.PropertyType.FullName.Replace("[]", string.Empty), false);

                for (int i = 0; i < curArrayList.Count; i++)
                {
                    curRootObject           = ReflectionUtil.CreateInstance(elementType);
                    curRootObjectProperties = curArrayList[i];

                    typeCache = ReflectionUtil.GetCache(elementType);

                    foreach (KeyValuePair <string, string> kvp in curRootObjectProperties)
                    {
                        ReflectionUtil.SetPropertyPathValue(curRootObject, kvp.Key, kvp.Value);

                        // also set the "Specified"-flag, if any
                        piSpecified = typeCache.GetProperty(kvp.Key + "Specified", false);
                        if (piSpecified != null)
                        {
                            piSpecified.SetValue(curRootObject, true, null);
                        }
                    }

                    o[i] = curRootObject;
                }

                ReflectionUtil.SetPropertyPathValue(ret, arrayPropertyName, o);
            }

            return(ret);
        }
        protected virtual object CreateInstance(CreationContext context, ConstructorCandidate constructor, object[] arguments)
        {
            object instance = null;

            var implType = Model.Implementation;

            var createProxy    = Kernel.ProxyFactory.ShouldCreateProxy(Model);
            var createInstance = true;

            if (createProxy == false && Model.Implementation.IsAbstract)
            {
                throw new ComponentRegistrationException(
                          string.Format(
                              "Type {0} is abstract.{2} As such, it is not possible to instansiate it as implementation of service '{1}'. Did you forget to proxy it?",
                              Model.Implementation.FullName,
                              Model.Name,
                              Environment.NewLine));
            }

            if (createProxy)
            {
                createInstance = Kernel.ProxyFactory.RequiresTargetInstance(Kernel, Model);
            }

            if (createInstance)
            {
                try
                {
#if (SILVERLIGHT)
                    instance = ReflectionUtil.CreateInstance <object>(implType, arguments);
#else
                    if (useFastCreateInstance)
                    {
                        instance = FastCreateInstance(implType, arguments, constructor);
                    }
                    else
                    {
                        instance = implType.CreateInstance <object>(arguments);
                    }
#endif
                }
                catch (Exception ex)
                {
                    if (arguments != null)
                    {
                        foreach (var argument in arguments)
                        {
                            Kernel.ReleaseComponent(argument);
                        }
                    }

                    throw new ComponentActivatorException(
                              "ComponentActivator: could not instantiate " + Model.Implementation.FullName, ex);
                }
            }

            if (createProxy)
            {
                try
                {
                    instance = Kernel.ProxyFactory.Create(Kernel, instance, Model, context, arguments);
                }
                catch (Exception ex)
                {
                    if (arguments != null)
                    {
                        foreach (var argument in arguments)
                        {
                            Kernel.ReleaseComponent(argument);
                        }
                    }
                    throw new ComponentActivatorException("ComponentActivator: could not proxy " + Model.Implementation.FullName, ex);
                }
            }

            return(instance);
        }
Exemplo n.º 16
0
        private TRequested CreateInstance <TRequested>(Type implementor)
        {
            var requestedInstance = (TRequested)ReflectionUtil.CreateInstance(implementor);

            return(requestedInstance);
        }