Reflection.Emit实现接口的泛型方法约束

时间:2018-03-22 16:29:38

标签: c# generics interface reflection.emit type-constraints

我尝试使用System.Reflection.Emit动态生成接口的实现。为了能够生成泛型方法的实现,我必须正确地将接口方法的所有泛型参数约束应用于实现它的生成类中的方法,但是我无法弄清楚我做错了什么。类约束。

尝试构建类型时,我收到以下错误(已翻译):

  

System.TypeLoadException:'方法"错误"在类型" TestImplementation" of Assembly" TestAsm,Version = 0.0.0.0,Culture = neutral,PublicKeyToken = null"试图隐式地实现一个对类型参数的约束较弱的接口方法。'

这是一个简单的示例界面:

public interface ITest
{
    //Base type constraint seems to cause issues, also reproduces with other classes
    void Error<T>() where T : Encoding;

    // these all work as expected when code is generated for them
    //Task<T> A<T>(T input) where T : struct;
    //Task<T> B<T>(T input) where T : class, new();
    //Task<T> C<T>(T input) where T : IComparable<string>, IComparable, ICloneable;
}

这是类型生成器:

internal class Program
{
    private static Type Build()
    {
        // quite a lot of boilerplate is necessary for this, sorry!
        var asm = AssemblyBuilder.DefineDynamicAssembly(new AssemblyName("TestAsm"), AssemblyBuilderAccess.Run);
        var module = asm.DefineDynamicModule(asm.GetName().Name);


        var type = module.DefineType(
            "TestImplementation",
            TypeAttributes.Class | TypeAttributes.Public | TypeAttributes.AutoLayout | TypeAttributes.AnsiClass | TypeAttributes.BeforeFieldInit,
            typeof(object),
            new[] { typeof(ITest) }
        );
        var method = typeof(ITest).GetMethod("Error");

        var m = type.DefineMethod(
            method.Name,
            MethodAttributes.Public | MethodAttributes.Final | MethodAttributes.HideBySig | MethodAttributes.Virtual | MethodAttributes.NewSlot,
            CallingConventions.Standard | CallingConventions.HasThis,
            typeof(void),
            new Type[0]
        );

        //this is where the constraints are applied, I assume something is missing here
        var constraint = method.GetGenericArguments()[0];
        var constraintBuilder = m.DefineGenericParameters("T")[0];

        constraintBuilder.SetBaseTypeConstraint(constraint.BaseType);
        constraintBuilder.SetInterfaceConstraints(constraint.GetInterfaces());
        constraintBuilder.SetGenericParameterAttributes(constraint.GenericParameterAttributes);
        foreach (var attribute in BuildCustomAttributes(constraint.GetCustomAttributesData()))
        {
            constraintBuilder.SetCustomAttribute(attribute);
        }

        // dummy method body
        var il = m.GetILGenerator();
        il.EmitWriteLine("Sucess!");
        il.Emit(OpCodes.Ret);

        //fails right here \/
        return type.CreateType();
    }

    // I don't think attributes are actually necessary, but just in case..
    private static IEnumerable<CustomAttributeBuilder> BuildCustomAttributes(IEnumerable<CustomAttributeData> customAttributes)
    {
        return customAttributes.Select(attribute =>
        {
            var attributeArgs = attribute.ConstructorArguments.Select(a => a.Value).ToArray();
            var namedPropertyInfos = attribute.NamedArguments.Select(a => a.MemberInfo).OfType<PropertyInfo>().ToArray();
            var namedPropertyValues = attribute.NamedArguments.Where(a => a.MemberInfo is PropertyInfo).Select(a => a.TypedValue.Value).ToArray();
            var namedFieldInfos = attribute.NamedArguments.Select(a => a.MemberInfo).OfType<FieldInfo>().ToArray();
            var namedFieldValues = attribute.NamedArguments.Where(a => a.MemberInfo is FieldInfo).Select(a => a.TypedValue.Value).ToArray();
            return new CustomAttributeBuilder(attribute.Constructor, attributeArgs, namedPropertyInfos, namedPropertyValues, namedFieldInfos, namedFieldValues);
        });
    }

    private static void Main(string[] args)
    {
        var t = Build();
        var instance = (ITest)Activator.CreateInstance(t);
        instance.Error<List<object>>();
    }
}

我尝试过的事情:

  • 之前添加了我认为不必要的CustomAttributes生成
  • 阅读有关发布泛型类型和方法的MSDN文章,但这并没有帮助我弄清楚为什么约束不等同
  • 尝试了其他可能的约束,只有基类约束似乎失败
  • constraint
  • 使用constraint.BaseType代替SetBaseTypeConstraint
  • 使用TypeBuilder.CreateMethodOverride使用显式实现,这只会更改来自&#39;隐含&#39;的错误消息。明确&#39;
  • 将示例项目创建为.net框架应用程序,而不是.net标准类库

我的约束生成中是否缺少某些内容?我期望调用constraintBuilder.SetBaseTypeConstraint(constraint.BaseType);来设置基类的约束。

1 个答案:

答案 0 :(得分:1)

设置任何接口约束会覆盖BaseType约束或导致误导性错误消息。这解决了这个问题:

if(constraint.BaseType != null)
{
    constraintBuilder.SetBaseTypeConstraint(constraint.BaseType);
}
else
{
    constraintBuilder.SetInterfaceConstraints(constraint.GetInterfaces());
}

这似乎反直觉,因为我现在应用FEWER约束来修复错误,说我施加的限制太少。这也适用于

之类的声明
void Test<T>() where T: Example, IComparable<Example>`

即使我认为它不会,因为如果存在基类约束,我不再应用接口约束。这看起来很奇怪,所以我决定进一步调查并得出结论,返回正确接口的GetInterfaces()方法是巧合或实现细节。文档没有提到这一点,而是建议使用GetGenericParameterConstraints方法。

这是我最终实施的解决方案:

constraintBuilder.SetBaseTypeConstraint(constraint.BaseType);
constraintBuilder.SetInterfaceConstraints(constraint.GetInterfaces());

替换为

var interfaceList = new List<Type>();
foreach (var restriction in constraint.GetGenericParameterConstraints())
{
        if (restriction.IsClass)
        {
                constraintBuilder.SetBaseTypeConstraint(restriction);
        }
        else
        {
                interfaceList.Add(restriction);
        }
}

if (interfaceList.Count > 0)
{
        constraintBuilder.SetInterfaceConstraints(interfaceList.ToArray());
}