执行扩展方法





5.00/5 (11投票s)
一组支持条件表达式体函数和属性的扩展方法。
引言
表达式主体函数和属性是 C# 6.0 的一项特性。这项技术的局限性在于,它只能包含单个语句,即使是一个简单的 if
语句仍然是多行的。
代码
以下是我创建的三个扩展方法,用于执行一行代码
public static void ExecuteIfTrue(this bool value, Action action)
{
if (value) action();
}
public static void ExecuteIfFalse(this bool value, Action action)
{
if (!value) action();
}
public static void Execute(this bool value, Action actionTrue, Action actionFalse = null)
{
if (value) actionTrue();
else actionFalse?.Invoke();
}
Using the Code
以下是在属性中使用这些扩展方法之一的简单示例
private void DisplayMessageBox() => Flag.ExecuteIfTrue(
() => MessageBox.Show("The Flag is set to true"));
另一个使用 true 和 false lambda 表达式的示例
public void Execute(object parameter) => (parameter != null).Execute(() => _action(parameter),() =>_action("-1") );
示例
该示例是一个非常简单的程序,只有在选中 CheckBox
时,单击 Button
时才会显示一个 MessageBox
。
这些扩展方法在 ViewModel
中用于按钮的 ICommand
,以及在 RelayCommand
类中。
历史
- 2016/04/19:初始版本
- 2016/04/21:文章更新