简体   繁体   English

表达式树不支持动态泛型类型参数吗?

[英]Doesn't Expression Tree support dynamic generic type parameters?

I'd like to dynamically create generic classes. 我想动态创建泛型类。 To define type parameters you will call DefineGenericParameters method on TypeBuilder s and you can add type constraints on the type parameters with the return value. 要定义类型的参数,你会打电话给DefineGenericParameters的方法TypeBuilder S和您可以在类型参数与返回值的类型添加约束。

By the way, I'm using Expression Tree to emit the method body. 顺便说一句,我正在使用表达式树来发出方法主体。 But then I realized that the APIs of Expression Tree don't accept GenericTypeParameterBuilder s, which is the return value of the DefineGenericParameters method, as arguments. 但是后来我意识到,表达式树的API不接受GenericTypeParameterBuilder s作为参数,这是DefineGenericParameters方法的返回值。
Maybe you are wondering whether it will compile. 也许您想知道它是否可以编译。 Because the type is derived from Type so it will compile. 由于该类型源自Type所以它会编译。 But the APIs of Expression Tree throw exceptions at runtime, telling me that the type contains a generic type parameter on Mono and that the method is not supported on .NET. 但是表达式树的API在运行时引发异常,告诉我该类型在Mono上包含通用类型参数,而.NET不支持该方法。

So it seems to me that Expression Tree can't handle generic type parameters, but is it really so? 因此在我看来,表达式树无法处理泛型类型参数,但事实确实如此吗? Am I missing something? 我想念什么吗?
If so, I will be happy if you are suggesting other ways to handle generic type parameters using Expression Tree. 如果是这样,如果您建议使用表达式树处理通用类型参数的其他方法,我将很高兴。

the method is not supported on .NET. .NET不支持该方法。

This I can explain: 我可以解释一下:

To check if the type is an enum, in the end this line is called: 要检查类型是否为枚举,最后将此行称为:

public override bool IsSubclassOf(Type c)
{
    throw new NotSupportedException();
}

by this line: 通过这一行:

 public virtual bool IsEnum {
     get
     {
        return IsSubclassOf(RuntimeType.EnumType);
     }

that is called by this line: 行称为:

internal static ParameterExpression Make(Type type, string name, bool isByRef) {
    if (isByRef) {
        return new ByRefParameterExpression(type, name);
    } else {
        if (!type.IsEnum) {

Now... About your question: no can do. 现在...关于您的问题:不能做。 Sadly the two subsystems ( Reflection.Emit and Expression ) aren't much "compatible". 不幸的是,这两个子系统( Reflection.EmitExpression )并没有太多的“兼容”。 As you know creating instance methods (including constructors) with LambaExpression.CompileToMethod() isn't supported. 如您所知,不支持使用LambaExpression.CompileToMethod()创建实例方法(包括构造函数)。 The only thing you can do is create plain (non-generic) static methods that don't include the type being constructed with TypeBuilder in its parameters. 您唯一可以做的就是创建普通的(非泛型)静态方法,这些方法在其参数中不包括使用TypeBuilder构造的类型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM