简体   繁体   中英

Why does extracting a value to a 'var' variable change behaviour?

I am using EasyMoq ( http://wp7fx.codeplex.com/ ) as a mocking framework in a Windows Store application. In the setup code for a test case, I have code that looks like this:

var mock = Easy.Moq.Mock<SomeClass>();
mock.Setup(m => m.SomeMethod("an arg", Allow.Any<AnotherClass>())).Returns("a value");

This code works properly. For those of you not familiar with EasyMoq, Easy.Moq.Mock<...>() instantiates a mock and mock.Setup(m => m.XYZ()).Returns(...) configures the mock to return a value when it receives a call to the mock's XYZ() method. The Allow.Any<T>() expression indicates that it should match on any value. By looking at its source code, apparently it simply returns default(T) . The details are not that important.

Because that was a very long statement, I decided to break it up by extracting the Allow.Any<...>() expression into an implicitly variable, like so:

var mock = Easy.Moq.Mock<SomeClass>();
var arg = Allow.Any<AnotherClass>();
mock.Setup(m => m.SomeMethod("an arg", arg)).Returns("a value");

However, this code fails due to an System.NullReferenceException after invoking the method on the mock. It's probably a bug in EasyMoq, but my question is this:

How could this refactoring alter the behaviour of the code?

我愿意打赌.Setup签名涉及表达式...它可能将输入检查为表达式并对它们进行评估...并且因为你的var语句(var无关紧要) Allow.Any<T> call,表达式然后解析default(T)而不是Allow.Any<T> ...你能告诉我们.Setup签名吗?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM