将属性包含在谓词中时出现异常

我正在尝试比较具有多个属性的两个对象,但需要使用谓词来比较特定属性(object1在 处没有这些属性的确切值object2,因此我需要在那里比较部分字符串)。

所以,我正在尝试:

object1.Should().BeEquivalentTo(object2, options => options
    .Including(o => o.Property1.StartsWith("something"))
    .Including(o => o.Property2.StartsWith("something else")
);

我希望所有其他属性都能像往常一样进行比较。

然而,运行上面的代码会抛出异常:

消息:System.ArgumentException:表达式<Convert(o.Property1.StartsWith("something"), Object)>不能用于选择成员。参数名称:表达式

为什么会出现此异常以及如何修复它?


至尊宝的传说
浏览 88回答 1
1回答

LEATH

为什么会出现这个异常发生异常是因为您正在调用函数.Including(o => o.Property1.StartsWith("something")) //<-- expects property only在仅期望获得属性表达式的表达式中。.Including(o => o.Property1) //<-- expects property only引用原始问题中链接的相同文档,您的示例在进行比较时将仅包含指定的成员。对于您想要做的事情,您应该查看该Equivalency Comparison Behavior部分,根据您的评论,该部分可能类似于以下示例[TestClass]public class ObjectEquivalencyTests {&nbsp; &nbsp; [TestMethod]&nbsp; &nbsp; public void ShouldBeEquivalent() {&nbsp; &nbsp; &nbsp; &nbsp; var expected = new MyObject {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Property1 = "https://www.google.com",&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Property2 = "something else"&nbsp; &nbsp; &nbsp; &nbsp; };&nbsp; &nbsp; &nbsp; &nbsp; var actual = new MyObject {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Property1 = "https://www.google.com/search?q=test",&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Property2 = "something else"&nbsp; &nbsp; &nbsp; &nbsp; };&nbsp; &nbsp; &nbsp; &nbsp; actual.Should().BeEquivalentTo(expected, options => options&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .Using<string>(ctx => ctx.Subject.Should().StartWith(ctx.Expectation))&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .When(info => info.SelectedMemberPath == "Property1")&nbsp; &nbsp; &nbsp; &nbsp; );&nbsp; &nbsp; }}public class MyObject {&nbsp; &nbsp; public string Property1 { get; set; }&nbsp; &nbsp; public string Property2 { get; set; }}
打开App,查看更多内容
随时随地看视频慕课网APP