对于这个问题,考虑(创建)界面:
public interface ITestMe
{
string TakeInt64(long x);
}
然后运行以下代码:
public void Test()
{
var mock1 = new Mock<ITestMe>(MockBehavior.Strict);
Expression<Func<ITestMe, string>> expr1 = x => x.TakeInt64(2);
Console.WriteLine(expr1);
mock1.Setup(expr1).Returns("OK");
var s1 = mock1.Object.TakeInt64(2L); // OK
var mock2 = new Mock<ITestMe>(MockBehavior.Strict);
Expression<Func<ITestMe, string>> expr2 = x => x.TakeInt64(DateTime.Today.Year / 1000);
Console.WriteLine(expr2);
mock2.Setup(expr2).Returns("OK");
var s2 = mock2.Object.TakeInt64(2L); // OK
var mock3 = new Mock<ITestMe>(MockBehavior.Strict);
Expression<Func<ITestMe, string>> expr3 = x => x.TakeInt64((int)(DayOfWeek)Enum.Parse(typeof(DayOfWeek), "Tuesday"));
Console.WriteLine(expr3);
mock3.Setup(expr3).Returns("OK");
var s3 = mock3.Object.TakeInt64(2L); // OK
var mock4 = new Mock<ITestMe>(MockBehavior.Strict);
Expression<Func<ITestMe, string>> expr4 = x => x.TakeInt64(GetInt32());
Console.WriteLine(expr4);
mock4.Setup(expr4).Returns("OK");
//var s4 = mock4.Object.TakeInt64(2L); // MockException, All invocations on the mock must have a corresponding setup.
var mock5 = new Mock<ITestMe>(MockBehavior.Strict);
Expression<Func<ITestMe, string>> expr5 = x => x.TakeInt64(int.Parse("2"));
Console.WriteLine(expr5);
mock5.Setup(expr5).Returns("OK");
//var s5 = mock5.Object.TakeInt64(2L); // MockException, All invocations on the mock must have a corresponding setup.
var mock6 = new Mock<ITestMe>(MockBehavior.Strict);
Expression<Func<ITestMe, string>> expr6 = x => x.TakeInt64(GetInt32() + 0);
Console.WriteLine(expr6);
mock6.Setup(expr6).Returns("OK");
var s6 = mock6.Object.TakeInt64(2L); // OK
var mock7 = new Mock<ITestMe>(MockBehavior.Strict);
Expression<Func<ITestMe, string>> expr7 = x => x.TakeInt64(1 * int.Parse("2"));
Console.WriteLine(expr7);
mock7.Setup(expr7).Returns("OK");
var s7 = mock7.Object.TakeInt64(2L); // OK
}
static int GetInt32()
{
return 2;
}
在所有七种情况下,我们都创建了一个表达式树,其中TakeInt64
得到一个int
( Int32
) 而不是long
( Int64
)。然而,众所周知,表达式树中存在隐式转换(编译器为我们转换常量的地方除外)int
。long
expr1
案例s4
及s5
以上怎么行不通?奇怪的是,正如您所看到的,如果我们在 case和中添加0
或相乘,那是否有效(即使类型仍然是,隐式转换为)?1
s6
s7
int
long
由于案例,请在 3000 年前回答expr2
。