Beispiel #1
0
        /// <summary>
        /// Creates an instance of <paramref name="type"/>.
        /// </summary>
        /// <param name="type">The <see cref="Type"/> of object to create</typeparam>
        /// <returns>An instance of <paramref name="type"/>.</returns>
        public static object CreateInstance(Type type)
        {
            Guard.ArgumentNotNull(type, "type");

            ConstructorDelegate _activator = null;

            if (!_activators.TryGetValue(type, out _activator))
            {
                var _constructor = type.GetConstructor(BindingFlags.Public | BindingFlags.Instance, null, EMPTY_PARAMETER_TYPE, null);
                if (_constructor == null)
                {
                    _constructor = type.GetConstructor(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance, null, EMPTY_PARAMETER_TYPE, null);
                }
                _activator = CreateConstructorDelegate(_constructor);
                lock (_lock)
                {
                    // double check and add
                    if (!_activators.ContainsKey(type))
                    {
                        _activators.Add(type, _activator);
                    }
                }
            }

            // and return
            return(_activator());
        }
Beispiel #2
0
 /// <summary>
 /// Initializes a new instance of the <see cref="Constructor"/> class.
 /// </summary>
 /// <param name="delegate">The delegate.</param>
 public Constructor(ConstructorDelegate @delegate)
 {
     ConstructorDelegate = @delegate;
     ParameterLength     = 0;
     Parameters          = Array.Empty <Type>();
     ParameterNullable   = Array.Empty <bool>();
 }
Beispiel #3
0
        private static ReadOnlyDictionary <string, Constructor> BuildControllerMap()
        {
            var attribType       = typeof(StateControllerNameAttribute);
            var constructortypes = new[] { typeof(StateSystem), typeof(string), typeof(TextSection) };

            var controllermap = new Dictionary <string, Constructor>(StringComparer.OrdinalIgnoreCase);

            foreach (var t in Assembly.GetCallingAssembly().GetTypes())
            {
                if (t.IsSubclassOf(typeof(StateController)) == false || Attribute.IsDefined(t, attribType) == false)
                {
                    continue;
                }
                var attrib = (StateControllerNameAttribute)Attribute.GetCustomAttribute(t, attribType);

                foreach (var name in attrib.Names)
                {
                    if (controllermap.ContainsKey(name))
                    {
                        Log.Write(LogLevel.Warning, LogSystem.StateSystem, "Duplicate definition found for state controller - {0}.", name);
                    }
                    else
                    {
                        controllermap.Add(name, ConstructorDelegate.FastConstruct(t, constructortypes));
                    }
                }
            }

            return(new ReadOnlyDictionary <string, Constructor>(controllermap));
        }
Beispiel #4
0
        /// <summary>
        /// Регистрация нового объекта игрового уровня.
        /// </summary>
        /// <param name='levelObject'>
        /// Игровой объект.
        /// </param>
        public void Register(String name, ConstructorDelegate constructorDelegate)
        {
            if (m_AllDelegates.ContainsKey(name) || null == constructorDelegate)
            {
                return;
            }

            m_AllDelegates.Add(name, constructorDelegate);
        }
        public void Set <T>(ConstructorDelegate <T> constructor) where T : class
        {
            if (deps.ContainsKey(typeof(T)))
            {
                return;
            }
            var dep = new Dependency <T>(constructor());

            deps.Add(typeof(T), dep);
        }
Beispiel #6
0
        public UndoableObservableCollection(ObservableCollection <SourceT> source, ConstructorDelegate ctor)
        {
            _ctor   = ctor;
            _source = source;

            // Initialize from source
            this.AddRange(source.Select(s => _ctor(s)));

            _source.CollectionChanged += source_CollectionChanged;
        }
Beispiel #7
0
        /// <summary>
        /// Возвращает объект игрового уровня по его описателю.
        /// </summary>
        /// <returns>
        /// Объект игрового уровня, либо null, если соответствующего описателю объекта не найдено.
        /// </returns>
        /// <param name='sObjectDescriptor'>
        /// Описатель объекта.
        /// </param>
        public SelfRegistrable GetObjectByDescriptor(String name)
        {
            if (!m_AllDelegates.ContainsKey(name))
            {
                return(null);
            }

            ConstructorDelegate constructorDelegate = m_AllDelegates[name];

            return(constructorDelegate());
        }
Beispiel #8
0
 /// <summary>
 /// Creates a new instance of the safe constructor wrapper.
 /// </summary>
 /// <param name="constructorInfo">Constructor to wrap.</param>
 public SafeConstructor(ConstructorInfo constructorInfo)
 {
     _constructorInfo = constructorInfo;
     try
     {
         _constructor = DynamicReflectionManager.CreateConstructor(constructorInfo);
     }
     catch
     {
         _isOptimized = false;
     }
 }
Beispiel #9
0
 /// <summary>
 /// Creates a new instance of the safe constructor wrapper.
 /// </summary>
 /// <param name="constructorInfo">Constructor to wrap.</param>
 public SafeConstructor(ConstructorInfo constructorInfo)
 {
     _constructorInfo = constructorInfo;
     try
     {
         _constructor = DynamicReflectionManager.CreateConstructor(constructorInfo);
     }
     catch
     {
         _isOptimized = false;
     }
 }
        public Base Create <U>() where U : Base
        {
            ConstructorInfo ci = currentType.GetConstructor(BindingFlags.Instance |
                                                            BindingFlags.Public, null, Type.EmptyTypes, null);
            DynamicMethod dm = new DynamicMethod("CreateInstance", typeof(Base), Type.EmptyTypes, typeof(ClassReference));
            ILGenerator   il = dm.GetILGenerator();

            il.Emit(OpCodes.Newobj, ci);
            il.Emit(OpCodes.Ret);
            ConstructorDelegate del = (ConstructorDelegate)dm.CreateDelegate(typeof(ConstructorDelegate));

            return(del());
        }
Beispiel #11
0
        public static List <T> Map <T>(DataTable source) where T : class
        {
            List <T> mappedList = new List <T>();

            using (SqlDataMappingInfo <T> propMap = new SqlDataMappingInfo <T>())
            {
                try
                {
                    IEnumerable <PropertyInfo> properties = typeof(T).GetProperties();

                    if (properties != null && properties.Count() > 0)
                    {
                        properties = properties.Where(pi => pi.CanWrite);
                    }

                    if (properties == null || properties.Count() == 0)
                    {
                        return(null);
                    }

                    foreach (PropertyInfo prop in properties)
                    {
                        propMap.Add(prop, source.Columns);
                    }
                }
                catch (Exception) { }

                var constructor = new ConstructorDelegate <T>(() => (T)Activator.CreateInstance(typeof(T))); //CreateConstructor<T>();

                foreach (DataRow row in source.Rows)
                {
                    T map = constructor();// (T)Activator.CreateInstance(typeof(T));

                    #region set properties
                    foreach (SqlMappingInfo <T> mapping in propMap.Values) //(PropertyInfo propInfo in properties)
                    {
                        if (mapping?.SetValue == null || row.IsNull(mapping.ColumnNumber))
                        {
                            continue;
                        }

                        mapping.SetValue(map, row[mapping.ColumnNumber]);
                    }
                    #endregion set properties

                    mappedList.Add(map);
                }
            }
            return(mappedList);
        }
Beispiel #12
0
        /// <summary>
        /// Obtains cached constructor info or creates a new entry, if none is found.
        /// </summary>
        private static ConstructorDelegate GetOrCreateDynamicConstructor(ConstructorInfo constructorInfo)
        {
            ConstructorDelegate method = (ConstructorDelegate)constructorCache[constructorInfo];

            if (method == null)
            {
                method = DynamicReflectionManager.CreateConstructor(constructorInfo);
                lock (constructorCache)
                {
                    constructorCache[constructorInfo] = method;
                }
            }
            return(method);
        }
Beispiel #13
0
        public void ForObjectWithoutParametarlessConstructorExceptionIsThrown()
        {
            bool error = false;

            try
            {
                ConstructorDelegate.GetConstructor <Models.NoValidCtor>();
            }
            catch (Exception)
            {
                error = true;
            }

            Assert.True(error);
        }
        ConstructorDelegate GetConstructor(string typeName)
        {
            Type            t    = Type.GetType(typeName);
            ConstructorInfo ctor = t.GetConstructor(new Type[0]);

            string        methodName = t.Name + "Ctor";
            DynamicMethod dm         = new DynamicMethod(methodName, t, new Type[0], typeof(Activator));
            ILGenerator   lgen       = dm.GetILGenerator();

            lgen.Emit(OpCodes.Newobj, ctor);
            lgen.Emit(OpCodes.Ret);

            ConstructorDelegate creator = (ConstructorDelegate)dm.CreateDelegate(typeof(ConstructorDelegate));

            return(creator);
        }
        ///<summary>
        /// Creates a new delegate for the specified constructor.
        ///</summary>
        ///<param name="constructorInfo">the constructor to create the delegate for</param>
        ///<returns>delegate that can be used to invoke the constructor.</returns>
        public static ConstructorDelegate CreateConstructor(ConstructorInfo constructorInfo)
        {
            Guard.ArgumentNotNull(constructorInfo, "You cannot create a dynamic constructor for a null value.");

            bool skipVisibility = true; //!IsPublic(constructorInfo);

            System.Reflection.Emit.DynamicMethod dmGetter;
            Type[] argumentTypes = new Type[] { typeof(object[]) };
            dmGetter = CreateDynamicMethod(constructorInfo.Name, typeof(object), argumentTypes, constructorInfo, skipVisibility);
            ILGenerator il = dmGetter.GetILGenerator();

            EmitInvokeConstructor(il, constructorInfo, false);
            ConstructorDelegate ctor = (ConstructorDelegate)dmGetter.CreateDelegate(typeof(ConstructorDelegate));

            return(ctor);
        }
Beispiel #16
0
        protected ConstructorDelegate GetConstructor(string typeName)
        {
            // 获得 type 的默认构造函数的引用
            Type            t    = Type.GetType(typeName);
            ConstructorInfo ctor = t.GetConstructor(new Type[0]);

            // 创建 dynamic method
            string methodName = t.Name + "Ctor";
            // api compatibility level 要到 .net 4.x
            DynamicMethod dm          = new DynamicMethod(methodName, t, new Type[0], typeof(Activator));
            ILGenerator   ilGenerator = dm.GetILGenerator();

            ilGenerator.Emit(OpCodes.Newobj, ctor);
            ilGenerator.Emit(OpCodes.Ret);

            ConstructorDelegate creator = (ConstructorDelegate)dm.CreateDelegate(typeof(ConstructorDelegate));

            return(creator);
        }
Beispiel #17
0
        protected ConstructorDelegate GetConstructor(string TypeName)
        {
            //Get the defaul constructor of the type
            Type            t    = Type.GetType(TypeName);
            ConstructorInfo ctor = t.GetConstructor(new Type[0]);

            // create a new dynamic method that constructs and returns the type
            string        methodName = t.Name + "Ctor";
            DynamicMethod dm         = new DynamicMethod(methodName, t, new Type[0], typeof(Activator));
            ILGenerator   lgen       = dm.GetILGenerator();

            lgen.Emit(OpCodes.Newobj, ctor);
            lgen.Emit(OpCodes.Ret);

            //add delegate to dictionary and return
            ConstructorDelegate creator = (ConstructorDelegate)dm.CreateDelegate(typeof(ConstructorDelegate));

            //return a delegate to the method
            return(creator);
        }
Beispiel #18
0
        // Creates a new GObject wrapper
        // Actual assignment of the wrapper's pointer is
        // deferred until either InitWrapper() is called or the
        // Handle is requested (in which case a new object is
        // created).
        public Object()
        {
            // If we are not wrapping an existing GObject type,
            // then we are a subclass by definition
            isSubclass = IsManaged(this.GetType());

            // If not a subclass, register type
            // TODO: Is this necessary or just a waste or CPU time?
            if (!isSubclass)
            {
                GType.Register(ResolveGType(this.GetType()), this.GetType());
            }

            if (isSubclass)
            {
                // Make sure we initialise the class
                Console.WriteLine("Class Initialisation goes here!");
            }

            defaultConstructor = delegate() {
                return(g_object_new_with_properties(GType.Object, 0, IntPtr.Zero, null));
            };
        }
        static ConstructorDelegate GetConstructor <T>()
        {
            Type t = typeof(T);

            if (_constructorCache.ContainsKey(t))
            {
                return(_constructorCache[t]);
            }

            ConstructorInfo ctor = t.GetConstructor(new Type[0]);

            string        methodName = t.Name + "Ctor";
            DynamicMethod dm         = new DynamicMethod(methodName, t, new Type[0], typeof(Activator));
            ILGenerator   lgen       = dm.GetILGenerator();

            lgen.Emit(OpCodes.Newobj, ctor);
            lgen.Emit(OpCodes.Ret);

            ConstructorDelegate creator = (ConstructorDelegate)dm.CreateDelegate(typeof(ConstructorDelegate));

            _constructorCache[t] = creator;

            return(creator);
        }
 /// <summary>
 /// Creates a new instance of the safe constructor wrapper.
 /// </summary>
 /// <param name="constructorInfo">Constructor to wrap.</param>
 public SafeConstructor(ConstructorInfo constructorInfo)
 {
     this.constructorInfo = constructorInfo;
     this.constructor = GetOrCreateDynamicConstructor(constructorInfo);
 }
Beispiel #21
0
 /// <summary>
 /// Initializes a new instance of <see cref="TypeAccessor"/>.
 /// </summary>
 /// <param name="type">The type to access.</param>
 /// <param name="propertyFilter">A filter to filter out properties to access.</param>
 public TypeAccessor(Type type, Func <PropertyInfo, bool> propertyFilter = null)
 {
     Type  = type;
     _ctor = CreateConstructor(Type);
     _propertyAccessors = CreatePropertyAccessors(Type, propertyFilter);
 }
 /// <summary>
 /// Creates a new instance of the safe constructor wrapper.
 /// </summary>
 /// <param name="constructorInfo">Constructor to wrap.</param>
 public SafeConstructor(ConstructorInfo constructorInfo)
 {
     this.constructorInfo = constructorInfo;
     this.constructor     = GetOrCreateDynamicConstructor(constructorInfo);
 }
Beispiel #23
0
 public virtual void EachConstructor(ConstructorDelegate constructorDelegate)
 {
     foreach (ConstructorInfo constructor in ClassType.GetConstructors(bindingFlag))
     {
         constructorDelegate.Invoke(constructor);
     }
 }
 private static void CreateByLocalConstructor()
 {
     ConstructorDelegate de      = GetConstructor <StringBuilder>();
     StringBuilder       builder = de() as StringBuilder;
 }
Beispiel #25
0
        public static List <T> Map <T>(SqlDataReader source) where T : class
        {
            List <T> mappedList = new List <T>();

            if (source == null || !source.HasRows)
            {
                return(mappedList);
            }
            //Dictionary<PropertyInfo, string> propertyMap = new Dictionary<PropertyInfo, string>();
            //Dictionary<PropertyInfo, Action<T, object>> setMap = new Dictionary<PropertyInfo, Action<T, object>>();
            using (SqlDataMappingInfo <T> propMap = new SqlDataMappingInfo <T>())
            {
                try
                {
                    string[] columns = new string[source.FieldCount];
                    for (int i = 0; i < source.FieldCount; ++i)
                    {
                        columns[i] = source.GetName(i).ToUpper().Trim();
                    }

                    IEnumerable <PropertyInfo> properties = typeof(T).GetProperties();

                    if (properties != null && properties.Count() > 0)
                    {
                        properties = properties.Where(pi => pi.CanWrite);
                    }


                    if (properties == null || properties.Count() == 0)
                    {
                        return(null);
                    }

                    foreach (PropertyInfo prop in properties)
                    {
                        propMap.Add(prop, columns);
                    }
                }
                catch (Exception) { }

                var constructor = new ConstructorDelegate <T>(() => (T)Activator.CreateInstance(typeof(T)));

                do
                {
                    while (source.Read())
                    {
                        T map = constructor(); //(T)Activator.CreateInstance(typeof(T));

                        #region set properties
                        foreach (SqlMappingInfo <T> mapping in propMap.Values) //(PropertyInfo propInfo in properties)
                        {
                            if (mapping?.SetValue == null || source.IsDBNull(mapping.ColumnNumber))
                            {
                                continue;
                            }

                            mapping.SetValue(map, source.GetValue(mapping.ColumnNumber));
                        }
                        #endregion set properties

                        mappedList.Add(map);
                    }
                } while (source.NextResult());
            }
            return(mappedList);
        }
        /// <summary>
        /// Creates an instance of a type using the constructor.
        /// </summary>
        /// <typeparam name="T">Type of class.</typeparam>
        /// <param name="type">Type of class.</param>
        /// <returns>Created object instance.</returns>
        internal static T Create <T>(Type type) where T : class
        {
            ConstructorDelegate creator = CreateConstructorDelegate(type);

            return(creator() as T);
        }
Beispiel #27
0
 /// <summary>
 /// Регистрация делегата для создания объекта в фабрике объектов под указанным именем.
 /// </summary>
 /// <param name='name'>
 /// Имя, под которым будет вызываться новый объект из фабрики объектов.
 /// </param>
 /// <param name='ctor'>
 /// Делегат для создания объекта, который необходимо зарегистрировать.
 /// </param>
 static public void Register(String name, ConstructorDelegate constructorDelegate)
 {
     m_RegistrableFactory.Register(name, constructorDelegate);
 }
Beispiel #28
0
 private Clonable CloneImpl(ref List<CloneDelegate> cloneDelegates, Dictionary<Type, DynamicMethod> cloneMethods)
 {
     if (cloneDelegates == null)
     {
         cloneDelegates = new List<CloneDelegate>();
         for (var klass = GetType(); klass != null && cloneMethods.ContainsKey(klass); klass = klass.BaseType)
             cloneDelegates.Add((CloneDelegate)cloneMethods[klass].CreateDelegate(typeof(CloneDelegate), this));
     }
     if (_constructorDelegate == null)
         _constructorDelegate = (ConstructorDelegate)g_constructors[GetType()].CreateDelegate(typeof(ConstructorDelegate), this);
     var clone = _constructorDelegate();
     for (int i = 0; i < cloneDelegates.Count; ++i) cloneDelegates[i](clone);
     clone.Cloned();
     return clone;
 }