代码之家  ›  专栏  ›  技术社区  ›  zajer

Fakeitiasy用构造函数中的参数自定义属性伪造抽象类引发ArgumentException

  •  1
  • zajer  · 技术社区  · 7 年前

    我有以下例外:

    System.ArgumentException:“仅支持常量和一维数组表达式”

    试图用构造函数中接受参数的附加属性来伪造一些Abstract对象。

    var foo = A.Fake<SelfComplementaryCustomizableTupleConsumer>(
                opt => opt.WithAttributes(
                    () => new RequiredVariableNameAttribute(requiredVariableName,requiredVariableType)
                    )
                );
    

    值得一提的是,如果我不带参数调用构造函数,一切都很好。对我来说更重要的是,如果我用常数替换变量,问题也不会出现。

    完整代码:

    string requiredVariableName = "abc";
    Type requiredVariableType = typeof(string);
    
    
    var foo = A.Fake<SelfComplementaryCustomizableTupleConsumer>(
              opt => opt.WithAttributes(
                    () => new RequiredVariableNameAttribute(requiredVariableName,requiredVariableType)
                    )
             );
    var requiredVariables = foo.GetRequiredVariables();
    
    Assert.IsTrue(requiredVariables.TryGetValue(requiredVariableName, out Type tmp));
    
    1 回复  |  直到 7 年前
        1
  •  2
  •   Thomas Levesque    7 年前

    这是由于 how the attribute creation expression is analyzed .它不支持所有可能的表达式,因为它非常复杂。我想可以处理局部变量的情况,但代码在castle.core(fakeitiasy使用)中,所以不要期望很快得到修复。同时,如果可以,请在表达式中使用常量;如果不能,则另一种方法是手动构建表达式(使用 Expression.Lambda<Func<Attribute>>(...) )

    编辑:我打开了一个 issue 在城堡里。核心回购。

    推荐文章