c# - 有人可以解释这个 C# 结构 : base. Executed += (s, e) =>

标签 c# mvvm

我正在处理 Josh Smith's CommandSink Examplebase.Executed += (s, e) =>... 结构让我很困惑,有人能帮我弄清楚吗?

我的理解:

  • base.CanExecute是继承类CommandBinding上的事件
  • += 正在向该事件添加委托(delegate)
  • 委托(delegate)是跟在该行之后的匿名函数

我不明白的地方:

  • (s,e) 是那个函数的签名吗?
  • 变量s用在什么地方?

这里是上下文中的代码:

public class CommandSinkBinding : CommandBinding
    {
        #region CommandSink [instance property]

        ICommandSink _commandSink;

        public ICommandSink CommandSink
        {
            get { return _commandSink; }
            set
            {
                if (value == null)
                    throw new ArgumentNullException("Cannot set CommandSink to null.");

                if (_commandSink != null)
                    throw new InvalidOperationException("Cannot set CommandSink more than once.");

                _commandSink = value;

                base.CanExecute += (s, e) =>
                    {
                        bool handled;
                        e.CanExecute = _commandSink.CanExecuteCommand(e.Command, e.Parameter, out handled);
                        e.Handled = handled;
                    };

                base.Executed += (s, e) =>
                    {
                        bool handled;
                        _commandSink.ExecuteCommand(e.Command, e.Parameter, out handled);
                        e.Handled = handled;
                    };
            }
        } 
        ...

最佳答案

(s, e) 是事件处理程序的方法参数签名(在本例中是定义的匿名方法)

想想 (object Sender, EventArgs e)

s 参数没有在方法的其余部分使用,这很好。它必须在那里匹配预期的签名

base.CanExecute += (s, e) =>
                    {
                        bool handled;
                        e.CanExecute = _commandSink.CanExecuteCommand(e.Command, e.Parameter, out handled);
                        e.Handled = handled;
                    };

相当于做

base.CanExecute += new EventHandler(myMethod_CanExecute);

///....
protected void myMethod_CanExecute(object sender, EventArgs e)
{
    bool handled;
    e.CanExecute = _commandSink.CanExecuteCommand(e.Command, e.Parameter, out handled);
    e.Handled = handled;
};

关于c# - 有人可以解释这个 C# 结构 : base. Executed += (s, e) =>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/771385/

相关文章:

c# - 生成 HTML 文件的最简单方法是什么?

c# - 克隆匿名类型?

c# - 对传入数据包进行高效的多种类型检查

c# - 统一: Register and resolve class with generic type

wpf - 带有MS SQL Server的通用Windows应用

wpf - INotifyPropertyChanged 和 DependencyProperty 有什么关系?

wpf - 无法在 ComboBox WPF 中使用多选项目保存

c# - JsonConvert DeserializeObject 找不到 int 成员

c# - 创建新 View 时如何初始化 View 模型中的属性?

c# - 将事件绑定(bind)到 Item ViewModel