当前位置: 首页>>代码示例>>C#>>正文


C# ConstructorInfo.ParameterTypes方法代码示例

本文整理汇总了C#中System.Reflection.ConstructorInfo.ParameterTypes方法的典型用法代码示例。如果您正苦于以下问题:C# ConstructorInfo.ParameterTypes方法的具体用法?C# ConstructorInfo.ParameterTypes怎么用?C# ConstructorInfo.ParameterTypes使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在System.Reflection.ConstructorInfo的用法示例。


在下文中一共展示了ConstructorInfo.ParameterTypes方法的1个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: CreateDelegateForConstructor

        /// <summary>
        ///     This generates a Delegate for a constructor that is strongly typed to the constructor type itself
        ///     It does this by dynamically creating a call via reflection to a constructor and then casting that to the type
        ///     created.
        /// </summary>
        /// <param name="ctorInfo">the constructor info for a constructor.</param>
        /// <returns>A strongly typed delegate for creating new objects of a given type</returns>
        public static Delegate CreateDelegateForConstructor(ConstructorInfo ctorInfo)
        {
            if (ctorInfo == null || ctorInfo.DeclaringType == null)
            {
                throw new ArgumentNullException(nameof(ctorInfo));
            }

            // Get the parameter types for the constructor
            var parameterTypes = ctorInfo.ParameterTypes();

            // Create a set of parameters for the expression
            Expression[] pars = parameterTypes.Select(Expression.Parameter).ToArray();

            // create the call to the constructor 
            Expression expression = Expression.Call(Expression.Constant(ctorInfo),
                typeof(ConstructorInfo).GetMethod("Invoke", new[] {typeof(object[])}),
                Expression.NewArrayInit(typeof(object), pars.Select(each => Expression.TypeAs(each, typeof(object)))));

            // wrap the return type to return the actual declaring type.
            expression = Expression.TypeAs(expression, ctorInfo.DeclaringType);

            // create a Func<...> delegate type for the lambda that we actually want to create
            var funcType = Expression.GetFuncType(parameterTypes.ConcatSingleItem(ctorInfo.DeclaringType).ToArray());

            // dynamically call Lambda<Func<...>> to create a type specific lambda expression 
            //Expression.Lambda<Func<object>>()
            var lambda = (LambdaExpression)LambdaMethodInfo.MakeGenericMethod(funcType).Invoke(null, new object[] {expression, pars});

            // return the compiled lambda
            return lambda.Compile();
        }
开发者ID:devigned,项目名称:autorest,代码行数:38,代码来源:Factory.cs


注:本文中的System.Reflection.ConstructorInfo.ParameterTypes方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。