我想声明一个“空”的lambda表达式,它确实没有。
有没有办法在不需要DoNothing()
方法的情况下做这样的事情?
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());
有没有办法做到这一点?似乎没有必要采用无操作方法。
答案 0 :(得分:203)
Action doNothing = () => { };
答案 1 :(得分:20)
这是一个老问题,但我想我会添加一些我发现对这种情况有用的代码。我有一个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);
答案 2 :(得分:10)
这应该有效:
SomeMenuCommand = new RelayCommand(
x => {},
x => CanSomeMenuCommandExecute());
答案 3 :(得分:7)
假设您只需要一个委托(而不是表达式树),那么这应该有效:
SomeMenuCommand = new RelayCommand(
x => {},
x => CanSomeMenuCommandExecute());
(这不适用于表达式树,因为它有一个语句体。有关更多详细信息,请参阅C#3.0规范的第4.6节。)
答案 4 :(得分:1)
我不完全明白为什么你需要DoNothing方法。
你不能这样做:
SomeMenuCommand = new RelayCommand(
null,
x => CanSomeMenuCommandExecute());
答案 5 :(得分:0)
Action DoNothing = delegate { };
Action DoNothing2 = () => {};
我以前将Events初始化为不执行任何操作,因此它不为null,并且如果不进行订阅就调用它,则默认为“不执行任何功能”而不是null指针异常。
public event EventHandler<MyHandlerInfo> MyHandlerInfo = delegate { };