0
爲什麼這個工作Returns((string food) => eat(food))
雖然這不:Returns(food => eat(food))
?爲什麼Moq有時需要在返回中顯式的類型聲明?
全部工作示例:
class Program
{
static void Main(string[] args)
{
var animal = new Mock<IAnimal>();
Func<string, string> eat = food => $"Nom nom nom {food}";
// works
animal.Setup(a => a.Eat(It.IsAny<string>())).Returns(eat);
// works
animal.Setup(a => a.Eat(It.IsAny<string>())).Returns((string food) => eat(food));
//cannot convert lambda expression to type 'string' because it is not a delegate type
animal.Setup(a => a.Eat(It.IsAny<string>())).Returns(food => eat(food));
//cannot convert lambda expression to type 'string' because it is not a delegate type
animal.Setup(a => a.Eat(It.IsAny<string>())).Returns(food => $"Nom nom nom {food}");
}
}
public interface IAnimal
{
string Eat(string food);
}
這不是Moq需要這個,它是C#編譯器。 '.Returns'方法的大量重載(在我的計數中爲18)可能給編譯器提供了太多的選擇。另外,將來如果代碼無法正常工作(如在,不會編譯),請發佈實際的錯誤消息。在這種情況下,它是「無法將lambda表達式轉換爲'string'類型,因爲它不是委託類型」。 –
@ LasseV.Karlsen公平地說,錯誤被嵌入到代碼註釋中,儘管我同意它應該更明顯。 – DavidG
@ LasseV.Karlsen我明白了,但我只在Moq Returns函數中注意到這種行爲,並且我很好奇編譯器在沒有找到合適的方法調用時會何去何從。我預計與回報中的其他一些方法有衝突,但哪一個? –