아무것도하지 않는 “빈”람다 식을 선언하고 싶습니다. 방법이 필요하지 않고 이와 같은 작업을 수행 할 수있는 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());
이 작업을 수행하는 방법이 있습니까? 아무것도하지 않는 방법이 필요하지 않은 것 같습니다.
답변
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());