以下 3 种方法是我使用的库 FakeItEasy 的一部分:
public static T Matches<T>(this IArgumentConstraintManager<T> scope, Func<T, bool> predicate, string description);
public static T Matches<T>(this IArgumentConstraintManager<T> manager, Func<T, bool> predicate, string descriptionFormat, params object[] args);
public static T Matches<T>(this IArgumentConstraintManager<T> scope, Expression<Func<T, bool>> predicate);
我在使用 Visual Studio 2017 时遇到以下问题。我想提供一个谓词Func<T,bool>
not Expression<Func<T, bool>>
。原因是我的函数比较了一个类的动态属性,如下所示:
A.CallTo(() => A<Class>.That.Matches(obj => obj.DynamicProperty == "text")).MustHaveHappened();
DynamicProperty
用dynamic
关键字标记,我收到编译时错误说
表达式树可能不包含动态操作
https://i.imgur.com/ujetxPh.png好的,我明白了。它在表达式中不受支持。我想选择一个使用Func<T, bool>
.
如果有两种方法在谓词(表达式和函数)的类型上有所不同,我该如何选择一个?
正如你在上面的方法定义中看到的,Func<T,bool>
重载有一个额外的string description
参数。我希望这足以让编译器选择适当的重载。
所以我改变了我的电话是这样的:
A.CallTo(() => A<Class>.That.Matches(obj => obj.DynamicProperty == "text", "testing")).MustHaveHappened();
仍然得到相同的编译器时间错误,但是当我现在将鼠标悬停在 Visual Studio 中的方法上时,工具提示说选择的方法是那个Func<T,bool>
。那么为什么我仍然无法编译它并显示有关表达式树的错误信息?我不想使用任何表达式树!
因此,只有将谓词放在单独的方法中,我才设法使其编译
public bool Test(Class obj){
return obj.DynamicProperty == "text";
}
并将我的支票更改为
A.CallTo(() => A<Class>.That.Matches(Test, "testing")).MustHaveHappened();
这似乎可以解决问题。
但我仍然希望编译器将我使用 lamda 语法编写的函数视为Func<T,bool>
not Expression<Func<T,bool>>
。
这是 VS 或编译器中的错误还是我遗漏了什么?
编辑 - 重现它的步骤/设置
创建一个空白的控制台项目替换packages.config和Program.cs:
https://gist.github.com/michaelbudnik/33f3dd39df038ba1d02f01dc9659002b
编译器抱怨的表达式是“CallTo”方法的参数:
A.CallTo(() => mandrill.SendMessageTemplate(A<SendMessageTemplateRequest>.That.Matches(...)));
因此,选择哪种匹配重载并不重要。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句