简体   繁体   English

为什么要将值提取到'var'变量行为?

[英]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. 我使用EasyMoq( http://wp7fx.codeplex.com/ )作为Windows应用商店应用程序中的模拟框架。 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. 对于那些不熟悉EasyMoq的人, Easy.Moq.Mock<...>()实例化一个mock和mock.Setup(m => m.XYZ()).Returns(...)配置mock返回当它接收到对mock的XYZ()方法的调用时的值。 The Allow.Any<T>() expression indicates that it should match on any value. Allow.Any<T>()表达式表明它应匹配任何值。 By looking at its source code, apparently it simply returns default(T) . 通过查看其源代码,显然它只返回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: 因为这是一个非常长的语句,我决定通过将Allow.Any<...>()表达式Allow.Any<...>()压缩为隐式变量来解决它,如下所示:

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. 但是,在mock上调用方法后,由于System.NullReferenceException ,此代码失败。 It's probably a bug in EasyMoq, but my question is this: 这可能是EasyMoq中的一个错误,但我的问题是:

How could this refactoring alter the behaviour of the code? 这种重构怎么会改变代码的行为呢?

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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