示例#1
0
        public static MethodMap PrepareInvoke(Type type, string[] paramNames, Type[] parameterTypes,
                                              object[] sampleParamValues)
        {
            SourceInfo sourceInfo = new SourceInfo(type, paramNames, parameterTypes);
            MethodMap  map        = ctorMapCache.Get(sourceInfo);

            if (map == null)
            {
                map = DetermineBestConstructorMatch(type, paramNames, parameterTypes, sampleParamValues);
                ctorMapCache.Insert(sourceInfo, map);
            }
            return(map);
        }
        /// <summary>
        /// Creates an instance of the given <paramref name="type"/> using the public properties of the
        /// supplied <paramref name="sample"/> object as input.
        /// This method will try to determine the least-cost route to constructing the instance, which
        /// implies mapping as many properties as possible to constructor parameters. Remaining properties
        /// on the source are mapped to properties on the created instance or ignored if none matches.
        /// TryCreateInstance is very liberal and attempts to convert values that are not otherwise
        /// considered compatible, such as between strings and enums or numbers, Guids and byte[], etc.
        /// </summary>
        /// <returns>An instance of <paramref name="type"/>.</returns>
        public static object TryCreateInstance(this Type type, object sample)
        {
            Type       sourceType = sample.GetType();
            SourceInfo sourceInfo = sourceInfoCache.Get(sourceType);

            if (sourceInfo == null)
            {
                sourceInfo = new SourceInfo(sourceType);
                sourceInfoCache.Insert(sourceType, sourceInfo);
            }
            object[]  paramValues = sourceInfo.GetParameterValues(sample);
            MethodMap map         = MapFactory.PrepareInvoke(type, sourceInfo.ParamNames, sourceInfo.ParamTypes, paramValues);

            return(map.Invoke(paramValues));
        }