Creates an instance of the specified type using a generated factory to avoid using Reflection. - CSharp System

CSharp examples for System:Type

Description

Creates an instance of the specified type using a generated factory to avoid using Reflection.

Demo Code


using System.Reflection;
using System.Linq.Expressions;
using System.Linq;
using System.Collections.Generic;
using System;/*w w  w.ja v  a  2s  . c  o m*/

public class Main{
        public static object Create(Type type, params object[] arguments)
        {
            Func<object> f;

            if (!factoryCache.TryGetValue(type, out f))
                lock (factoryCache)
                    if (!factoryCache.TryGetValue(type, out f))
                    {
                        var ctor = type.GetConstructors().FirstOrDefault();

                        if (ctor != null)
                        {
                            var args = arguments.Select(a => Expression.Constant(a));
                            factoryCache[type] = f = Expression.Lambda<Func<object>>(Expression.New(ctor, args)).Compile();
                        }
                    }

            return f();
        }
        /// <summary>
        /// Creates an instance of the specified type using a generated factory to avoid using Reflection.
        /// </summary>
        /// <param name="type">The type to be created.</param>
        /// <returns>The newly created instance.</returns>
        public static object Create(Type type)
        {
            Func<object> f;

            if (!factoryCache.TryGetValue(type, out f))
                lock (factoryCache)
                    if (!factoryCache.TryGetValue(type, out f))
                    {
                        factoryCache[type] = f = Expression.Lambda<Func<object>>(Expression.New(type)).Compile();
                    }

            return f();
        }
        /// <summary>
        /// Creates an instance of the specified type using a generated factory to avoid using Reflection.
        /// </summary>
        /// <typeparam name="T">The type to be created.</typeparam>
        /// <returns>The newly created instance.</returns>
        public static T Create<T>()
        {
            return TypeFactory<T>.Create();
        }
}

Related Tutorials