在为List <t>编译构造函数时,“CLR检测到无效程序”

时间:2015-06-17 12:24:28

标签: c# .net linq lambda clr

在将无参数构造函数的lambda表达式编译为委托时,我遇到了一个奇怪的问题。它适用于我尝试过的几乎所有类型。只有List&lt;&gt;正在产生“CLR检测到无效程序”。收集&lt;&gt;或者来自List&lt;&gt;的继承类不会出现问题。

/// <summary>
/// Delegate for activating instances of objects.
/// </summary>
/// <param name="args">Arguments of the construtor.</param>
/// <returns>A new instance of the object.</returns>
public delegate Object InstanceActivator(params object[] args);

/// <summary>
/// Compiles an instance activator.
/// </summary>
/// <param name="objectType">Type of the object to be created.</param>
/// <param name="definition">Constructor parameters as string.</param>
/// <returns>An compiled instance activator to be used for activating new instances of the object.</returns>
public static InstanceActivator CompileDefaultConstructorToInstanceActivator(Type objectType)
{
    ConstructorInfo foundConstructor = default(ConstructorInfo);

    foreach (ConstructorInfo constructorInfo in objectType.GetTypeInfo().DeclaredConstructors)
    {
        if(constructorInfo.GetParameters().Length == 0)
        {
            foundConstructor = constructorInfo;
        }
    }

    ParameterInfo[] paramsInfo = foundConstructor.GetParameters();

    ParameterExpression parameter = Expression.Parameter(typeof(object[]), "args");

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

    NewExpression newExpression = Expression.New(foundConstructor, argumentExpressions);
    LambdaExpression lambda = Expression.Lambda(typeof(InstanceActivator), newExpression, parameter);

    return (InstanceActivator)lambda.Compile();
}

因此,当我以下列方式调用此方法时,它的效果非常好:

    [TestMethod]
    public void CreateGenericCollectionOfString()
    {
        Object activatedObject = Sandbox.Functions.Activator.CompileDefaultConstructorToInstanceActivator(typeof(Collection<String>))();

        Assert.IsNotNull(activatedObject);
        Assert.IsInstanceOfType(activatedObject, typeof(Collection<String>));
    }

但是以下测试会引发错误:

    [TestMethod]
    public void CreateGenericListOfString()
    {
        Object activatedObject = Sandbox.Functions.Activator.CompileDefaultConstructorToInstanceActivator(typeof(List<String>))();

        Assert.IsNotNull(activatedObject);
        Assert.IsInstanceOfType(activatedObject, typeof(List<String>));
    }

希望有人能解释一下这个原因。

我已经将示例项目上传了单元测试,将问题复制到GitHub。

https://github.com/teoturner/Sandbox/blob/master/Code/Functions/Activator.cs https://github.com/teoturner/Sandbox/blob/master/Code/Tests/ActivatorTests.cs

1 个答案:

答案 0 :(得分:2)

DeclaredConstructors属性甚至会返回List<>的静态构造函数。你显然无法援引它。

使用:

ConstructorInfo foundConstructor = objectType.GetTypeInfo().GetConstructor(Type.EmptyTypes);