c# – 为什么nameof()在Linq表达式中给出了一个模糊的调用警告,但是当我使用相同的值作为字符串时却没有?

当我升级到FluentAssertions 4.2.2时,我收到了一个编译器警告.在下面的代码中,如果我调用EndsWith(nameof(x)),我会得到一个模糊的调用警告.如果我定义var foo = nameof(x)并调用EndsWith(foo),它会干净地编译.代码在两种情况下都运行正常.

我的问题是为什么会发生这种情况,除了将nameof()结果存储在变量中之外,还有其他解决方法吗?

[Test]
public void TestLastNamesAreSame()
{
    var original = new MyDTO("fred", "jones");
    var expected = new MyDTO("barney", "jones");

    // this gives an Ambiguous invocation warning
    expected.ShouldBeEquivalentTo(original, o => o
        .Excluding(x => x.SelectedMemberPath.EndsWith(nameof(MyDTO.FirstName))));

    // but when I use a variable holding the same value, it works without warning
    const string nameOfFirstNameField = nameof(MyDTO.FirstName);
    expected.ShouldBeEquivalentTo(original, o => o
        .Excluding(x => x.SelectedMemberPath.EndsWith(nameOfFirstNameField)));
}

public class MyDTO
{
    public string FirstName { get; }
    public string LastName { get; }

    public MyDTO(string firstName, string lastName)
    {
        FirstName = firstName;
        LastName = lastName;
    }
}

最佳答案 您确定这是编译器错误/警告而不是ReSharper警告吗?

如果是前者,那么CSNNNN错误/警告号码是什么?

看看(Resharper: Ambiguous Invocation)

点赞