Nik*_*Nik 7 .net c# unit-testing visual-studio-2010
两个括号和箭头的目的是什么
service.GetDeviceLOV =()=>
我一直试图弄清楚它的功能.下面是用于单元测试的整个方法.希望这有助于提供它的背景.
//A test for GetDeviceTypes
[TestMethod()]
[HostType("Moles")]
public void GetDeviceTypesTest()
{
SetUpMoles();
Login ();
service.GetDeviceLOV = () =>
{
return new List<DeviceLOV>() {
new DeviceLOV{DeviceType = "Type 1"},
new DeviceLOV{DeviceType = "Type 2"},
new DeviceLOV {DeviceType = "Type 1"}
};
};
List<string> actual;
actual = presenter.GetDeviceTypes();
Assert.AreEqual(2, actual.Count ,"actual.Count Should = 2");
}
Run Code Online (Sandbox Code Playgroud)
这是一个lambda表达式,用于创建匿名函数的委托.
在您的情况下,该GetDeviceLOV
属性是一个委托,它返回一个List<DeviceLOV>
(或者它实现的某个接口,例如IEnumerable<DeviceLOV>
).
lambda表达式允许您内联编写"方法"并从中创建委托,并将其分配给该属性.如果没有这种语法,您需要创建一个单独的方法,并直接分配一个委托,即:
private List<DeviceLOV> MakeDeviceList()
{
return new List<DeviceLOV>
{
new DeviceLOV{DeviceType = "Type 1"},
new DeviceLOV{DeviceType = "Type 2"},
new DeviceLOV {DeviceType = "Type 1"}
};
};
Run Code Online (Sandbox Code Playgroud)
那你就写下这样的东西:
service.GetDeviceLOV = new Func<List<DeviceLOV>>(this.MakeDeviceList);
Run Code Online (Sandbox Code Playgroud)
lambda表达式允许您编写方法"inline",并直接指定它.它还提供了附加功能(在这种情况下不使用),因为它允许您引用局部变量(编译器将变成闭包)等.