有没有办法指定一个"空"的C#lambda表达式?

Rob*_*Rob 106 c# lambda

我想声明一个"空"的lambda表达式,它确实没有.有没有办法在不需要方法的情况下做这样的事情DoNothing()

    public MyViewModel()
    {
        SomeMenuCommand = new RelayCommand(
                x => DoNothing(),
                x => CanSomeMenuCommandExecute());
    }

    private void DoNothing()
    {
    }

    private bool CanSomeMenuCommandExecute()
    {
        // this depends on my mood
    }
Run Code Online (Sandbox Code Playgroud)

我这样做的意图只是控制我的WPF命令的启用/禁用状态,但这是暂且不说的.也许这对我来说太早了,但我想必须有办法以x => DoNothing()某种方式声明lambda表达式来完成同样的事情:

    SomeMenuCommand = new RelayCommand(
        x => (),
        x => CanSomeMenuCommandExecute());
Run Code Online (Sandbox Code Playgroud)

有办法做到这一点吗?似乎没有必要采用无操作方法.

Rau*_*otz 212

Action doNothing = () => { };
Run Code Online (Sandbox Code Playgroud)

  • 是否存在预定义的空 lambda?我认为每次需要时创建一个空的 lambda 从性能角度来说是一个坏主意。例如,在 JQuery 中[有 `noop`](/sf/ask/144854181/ Purpose-does-noop-serve-in-jquery-1-4),我希望有类似的东西出现在 C# 中。 (4认同)

Ant*_*ony 21

这是一个老问题,但我想我会添加一些我发现对这种情况有用的代码.我有一个Actions静态类和一个Functions静态类,其中包含一些基本功能:

public static class Actions
{
  public static void Empty() { }
  public static void Empty<T>(T value) { }
  public static void Empty<T1, T2>(T1 value1, T2 value2) { }
  /* Put as many overloads as you want */
}

public static class Functions
{
  public static T Identity<T>(T value) { return value; }

  public static T0 Default<T0>() { return default(T0); }
  public static T0 Default<T1, T0>(T1 value1) { return default(T0); }
  /* Put as many overloads as you want */

  /* Some other potential methods */
  public static bool IsNull<T>(T entity) where T : class { return entity == null; }
  public static bool IsNonNull<T>(T entity) where T : class { return entity != null; }

  /* Put as many overloads for True and False as you want */
  public static bool True<T>(T entity) { return true; }
  public static bool False<T>(T entity) { return false; }
}
Run Code Online (Sandbox Code Playgroud)

我相信这有助于提高可读性:

SomeMenuCommand = new RelayCommand(
        Actions.Empty,
        x => CanSomeMenuCommandExecute());

// Another example:
var lOrderedStrings = GetCollectionOfStrings().OrderBy(Functions.Identity);
Run Code Online (Sandbox Code Playgroud)


Jos*_*eph 10

这应该工作:

SomeMenuCommand = new RelayCommand(
    x => {},
    x => CanSomeMenuCommandExecute());
Run Code Online (Sandbox Code Playgroud)


Jon*_*eet 7

假设您只需要一个委托(而不是表达式树),那么这应该有效:

SomeMenuCommand = new RelayCommand(
        x => {},
        x => CanSomeMenuCommandExecute());
Run Code Online (Sandbox Code Playgroud)

(这不适用于表达式树,因为它有一个语句体.有关更多详细信息,请参阅C#3.0规范的4.6节.)