none
为何从表达式树Expression<>对象Compile而来的方法无法CreateDelegate? RRS feed

  • 问题

  • 请考虑以下的代码:

    public delegate int plus(int x);
    
    public void main()
    {
        Expression<Func<int, int>> expr = i => i + 1;
        expr.Compile().Method.CreateDelegate(typeof(plus));
    }

    在运行上述代码时,CreateDelegate方法会抛出一个NotSupportedException:派生类必须提供一个实现。

    这是为什么呢?

    2013年7月12日 6:04

答案

  • 根据反射情况,貌似这两个方法没有实现:

            [__DynamicallyInvokable]
            public virtual Delegate CreateDelegate(Type delegateType)
            {
                throw new NotSupportedException(Environment.GetResourceString("NotSupported_SubclassOverride"));
            }
    
            [__DynamicallyInvokable]
            public virtual Delegate CreateDelegate(Type delegateType, object target)
            {
                throw new NotSupportedException(Environment.GetResourceString("NotSupported_SubclassOverride"));
            }

    【解决方案】

    Expression<Func<intint>> expr = i => i + 1;
    Console.WriteLine(expr.Compile().Invoke(1));

    If you think one reply solves your problem, please mark it as An Answer, if you think someone's reply helps you, please mark it as a Proposed Answer

    Help by clicking:
    Click here to donate your rice to the poor
    Click to Donate
    Click to feed Dogs & Cats


    Found any spamming-senders? Please report at: Spam Report

    2013年7月13日 4:10

全部回复

  • 根据反射情况,貌似这两个方法没有实现:

            [__DynamicallyInvokable]
            public virtual Delegate CreateDelegate(Type delegateType)
            {
                throw new NotSupportedException(Environment.GetResourceString("NotSupported_SubclassOverride"));
            }
    
            [__DynamicallyInvokable]
            public virtual Delegate CreateDelegate(Type delegateType, object target)
            {
                throw new NotSupportedException(Environment.GetResourceString("NotSupported_SubclassOverride"));
            }

    【解决方案】

    Expression<Func<intint>> expr = i => i + 1;
    Console.WriteLine(expr.Compile().Invoke(1));

    If you think one reply solves your problem, please mark it as An Answer, if you think someone's reply helps you, please mark it as a Proposed Answer

    Help by clicking:
    Click here to donate your rice to the poor
    Click to Donate
    Click to feed Dogs & Cats


    Found any spamming-senders? Please report at: Spam Report

    2013年7月13日 4:10
  • 谢谢,我也发现是这个问题了。但是我希望将这一动态创建的方法赋值给特定的委托,您提供的解决方法恐怕还是没法实现。不过还是非常感谢 :)

    2013年7月13日 14:18