簡體   English   中英

有沒有辦法指定“空” C# lambda 表達式?

[英]Is there a way to specify an "empty" C# lambda expression?

我想聲明一個“空的” lambda 表達式,嗯,什么都不做。 有沒有辦法在不需要DoNothing()方法的情況下做這樣的事情?

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

private void DoNothing()
{
}

private bool CanSomeMenuCommandExecute()
{
    // this depends on my mood
}

我這樣做的目的只是控制我的 WPF 命令的啟用/禁用 state,但這是一個旁白。 也許現在對我來說還太早,但我想一定有一種方法可以像這樣以某種方式聲明x => DoNothing() lambda 表達式來完成同樣的事情:

SomeMenuCommand = new RelayCommand(
    x => (),
    x => CanSomeMenuCommandExecute());

有什么辦法可以做到這一點? 似乎不需要什么都不做的方法。

Action doNothing = () => { };

我想我會添加一些我發現對這種情況有用的代碼。 我有一個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; }
}

我相信這有助於提高可讀性只是一點點:

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

// Another example:
var lOrderedStrings = GetCollectionOfStrings().OrderBy(Functions.Identity);

這應該有效:

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

假設您只需要一個委托(而不是表達式樹),那么這應該可以工作:

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

(這不適用於表達式樹,因為它有一個語句體。有關更多詳細信息,請參閱 C# 3.0 規范的第 4.6 節。)

我不完全明白為什么你需要一個 DoNothing 方法。

你不能只做:

SomeMenuCommand = new RelayCommand(
                null,
                x => CanSomeMenuCommandExecute());
Action DoNothing = delegate { };
Action DoNothing2 = () => {};

我曾經將 Events 初始化為一個什么都不做的動作,所以它不是空的,如果它在沒有訂閱的情況下被調用,它將默認為“不做任何功能”而不是空指針異常。

public event EventHandler<MyHandlerInfo> MyHandlerInfo = delegate { };

從 C# 9.0 開始,您可以為所需參數指定丟棄_ 例子:

Action<int, string, DateTime> action = (_, _, _) => { };

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM