"빈"C # 람다 식을 지정하는 방법이 있습니까?


118

아무것도하지 않는 "빈"람다 식을 선언하고 싶습니다. 방법이 필요하지 않고 이와 같은 작업을 수행 할 수있는 DoNothing()방법이 있습니까?

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

private void DoNothing()
{
}

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

이 작업을 수행하려는 의도는 내 WPF 명령의 활성화 / 비활성화 상태를 제어하는 ​​것뿐입니다. 어쩌면 너무 이른 아침일지도 모르지만 선언 할 방법이있을 것 같습니다.x => DoNothing() , 똑같은 일을 달성하기 위해 람다 식을 다음과 같이 .

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

이 작업을 수행하는 방법이 있습니까? 아무것도하지 않는 방법이 필요하지 않은 것 같습니다.

답변:


231
Action doNothing = () => { };

미리 정의 된 빈 람다가 있습니까? 필요할 때마다 빈 람다를 만드는 것은 성능이 좋지 않다고 생각합니다. 예를 들어 JQuery 에는이 있고noop C #에 비슷한 것이있을 것으로 예상합니다.
qqqqqqq

그래서 이것의 비동기 버전은 자세한 정보가 필요 Func<Task> doNothing = async() => await Task.CompletedTask;합니까?
Patrick Szalapski

23

이것은 오래된 질문이지만 이러한 유형의 상황에 유용한 코드를 추가 할 것이라고 생각했습니다. 나는이 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);

10

이것은 작동합니다.

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

7

표현식 트리가 아닌 델리게이트 만 필요하다고 가정하면 다음과 같이 작동합니다.

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

( 문 본문 이 있기 때문에 식 트리에서는 작동하지 않습니다 . 자세한 내용은 C # 3.0 사양의 섹션 4.6을 참조하세요.)


2

DoNothing 메서드가 필요한 이유를 완전히 이해하지 못합니다.

당신은 할 수 없습니다 :

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

3
그것은 아마도 확인되고 아마도 NRE를 던질 것입니다.
Dykam

나는 Dykam이 옳다고 생각하지만 null을 전달하는 것에 대해 생각하지 않았습니다. :-)
Rob

1
왜 이것이 비추천인지 이해가 안 되나요? Jorge는 그것을 확인하기 위해 약간의 노력을 기울 였을지라도 유효한 지적을합니다.
Cohen

+1, 이것은 유효한 솔루션입니다. 단지 null 검사가 new RelayCommand(...
nawfal
당사 사이트를 사용함과 동시에 당사의 쿠키 정책개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.