Activator.CreateInstance

wcbaby發表於2018-09-30
   private Dictionary<Type, Type> m_ObjectType = new Dictionary<Type, Type>();


   public T CreateNewInstance<T>() where T : class
        {
            if (m_ObjectType.ContainsKey(typeof(T)))
            {
                Type insType = m_ObjectType[typeof(T)];
                return Activator.CreateInstance(insType) as T;
            }
            else
            {
                throw new Exception("未知的型別"+ typeof(T).ToString());
            }
        }

        public T CreateNewInstance<T>(params object[] args) where T:class
        {
            if (m_ObjectType.ContainsKey(typeof(T)))
            {
                Type insType = m_ObjectType[typeof(T)];
                return Activator.CreateInstance(insType, args) as T;
            }
            else
            {
                throw new Exception("未知的型別" + typeof(T).ToString());
            }
        }

   public IDatabaseItem CreateNewDatabaseItem(string name, string description, 
    DatabaseItemType tt, IDatabaseItem parent)
        {
            switch (tt)
            {
                case DatabaseItemType.Database:
                    return CreateNewInstance<DatabaseItem>(name, parent);
                case DatabaseItemType.Field:
                    return CreateNewInstance<DatabaseFieldItem>(name, description, 
                      parent);
                case DatabaseItemType.Server:
                    return CreateNewInstance<DatabaseServerItem>(name);
                case DatabaseItemType.Table:
                    return CreateNewInstance<DatabaseTableItem>(name, parent);
                default:
                    throw new Exception("未知的資料庫型別");
            }
        }

  

  •