用其类型实例化一个类

dot*_*ixx 1 c# reflection activator

我正在寻找一种比Activator.CreateInstance从其类型实例化类更快的方法。

我现在正在这样做:Activator.CreateInstance(typeof(LoginView));但它非常慢:我在实例化不同视图时看到一些滞后。

给我一个建议?我现在在谷歌上搜索了几个小时,但我没有找到比这更快的方法来完成我想做的事情..:/

多谢 (:

key*_*rdP 5

您可以按照本博客文章中的说明使用 Linq 表达式。在你的情况下,这将是

ConstructorInfo ctor = typeof(LoginView).GetConstructors().First();
ObjectActivator<LoginView> createdActivator = GetActivator<LoginView>(ctor);


LoginView instance = createdActivator();
Run Code Online (Sandbox Code Playgroud)

如果链接断开,这是ObjectActivator委托

delegate T ObjectActivator<T>(params object[] args);
Run Code Online (Sandbox Code Playgroud)

GetActivator方法

public static ObjectActivator<T> GetActivator<T>
    (ConstructorInfo ctor)
{
    Type type = ctor.DeclaringType;
    ParameterInfo[] paramsInfo = ctor.GetParameters();                  

    //create a single param of type object[]
    ParameterExpression param =
        Expression.Parameter(typeof(object[]), "args");

    Expression[] argsExp =
        new Expression[paramsInfo.Length];            

    //pick each arg from the params array 
    //and create a typed expression of them
    for (int i = 0; i < paramsInfo.Length; i++)
    {
        Expression index = Expression.Constant(i);
        Type paramType = paramsInfo[i].ParameterType;              

        Expression paramAccessorExp =
            Expression.ArrayIndex(param, index);              

        Expression paramCastExp =
            Expression.Convert (paramAccessorExp, paramType);              

        argsExp[i] = paramCastExp;
    }                  

    //make a NewExpression that calls the
    //ctor with the args we just created
    NewExpression newExp = Expression.New(ctor,argsExp);                  

    //create a lambda with the New
    //Expression as body and our param object[] as arg
    LambdaExpression lambda =
        Expression.Lambda(typeof(ObjectActivator<T>), newExp, param);              

    //compile it
    ObjectActivator<T> compiled = (ObjectActivator<T>)lambda.Compile();
    return compiled;
}
Run Code Online (Sandbox Code Playgroud)

与通用方法相比,使用此方法的一个优点是您可以轻松地将参数传递给构造函数,但缺点是代码更加冗长。