2009-11-16 44 views
82

我想聲明一個「空」的lambda表達式,它確實沒有。 有沒有辦法做這樣的事情,而不需要​​方法?有沒有辦法指定一個「空的」C#lambda表達式?

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

    private void DoNothing() 
    { 
    } 

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

我這樣做的目的只是控制我的WPF命令的啓用/禁用狀態,但這是一個問題。也許這是早上我還爲時過早,但我想一定有,只是宣佈在一些像這樣的方法來完成同樣的事情x => DoNothing() lambda表達式的方式:

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

有一些方法做這個?似乎沒有必要使用無所事事的方法。

回答

172
Action doNothing =() => { }; 
6

假設你只需要一個委託(而不是一個表達式樹),那麼這應該工作:

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

(因爲它有一個聲明體不會與表達式樹工作,見4.6。 。

10

的C#3.0規範的更多詳細信息)這應該工作:

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

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

你就不能這樣做:

SomeMenuCommand = new RelayCommand(
       null, 
       x => CanSomeMenuCommandExecute()); 
+1

這可能是檢查,可能會扔一個NRE。 – Dykam 2009-11-16 15:50:01

+0

我認爲Dykam是正確的,但我只是沒有考慮傳遞null :-) – 2009-11-16 17:53:06

+1

我不明白爲什麼這是downvoted? Jorge提出了一個有效的觀點,儘管要檢查它纔是一個小小的努力。 – Cohen 2011-10-19 12:57:35

12

這是一個老問題,但我想我會添加一些代碼,我發現有用的這種類型的情況。我有一個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); 
相關問題