在c#中使用两个空白括号后跟箭头的目的是什么

前端之家收集整理的这篇文章主要介绍了在c#中使用两个空白括号后跟箭头的目的是什么前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
两个括号和箭头的目的是什么

service.GetDeviceLOV = () =>

我一直试图弄清楚它的功能.下面是用于单元测试的整个方法.希望这有助于提供它的背景.

  1. //A test for GetDeviceTypes
  2. [TestMethod()]
  3. [HostType("Moles")]
  4. public void GetDeviceTypesTest()
  5. {
  6. SetUpMoles();
  7. Login ();
  8.  
  9.  
  10. service.GetDeviceLOV = () =>
  11. {
  12. return new List<DeviceLOV>() {
  13.  
  14. new DeviceLOV{DeviceType = "Type 1"},new DeviceLOV{DeviceType = "Type 2"},new DeviceLOV {DeviceType = "Type 1"}
  15.  
  16. };
  17. };
  18.  
  19.  
  20.  
  21. List<string> actual;
  22. actual = presenter.GetDeviceTypes();
  23.  
  24. Assert.AreEqual(2,actual.Count,"actual.Count Should = 2");
  25.  
  26. }

解决方法

这是一个 lambda expression,用于创建匿名函数的委托.

在您的情况下,GetDeviceLOV属性是一个委托,它返回List< DeviceLOV> (或者它实现的一些接口,例如IEnumerable< DeviceLOV>).

lambda表达式允许您内联编写“方法”并从中创建委托,并将其分配给该属性.如果没有这种语法,您需要创建一个单独的方法,并直接分配一个委托,即:

  1. private List<DeviceLOV> MakeDeviceList()
  2. {
  3. return new List<DeviceLOV>
  4. {
  5. new DeviceLOV{DeviceType = "Type 1"},new DeviceLOV {DeviceType = "Type 1"}
  6. };
  7. };

那你就写下这样的东西:

  1. service.GetDeviceLOV = new Func<List<DeviceLOV>>(this.MakeDeviceList);

lambda表达式允许您编写方法“inline”,并直接指定它.它还提供了附加功能(在这种情况下不使用),因为它允许您引用局部变量(编译器将变成闭包)等.

猜你在找的C#相关文章