什么是“多余的委托创作”?多余

2023-09-04 02:35:01 作者:乀我拽丶我骄傲

我要注册一个事件在我的课,并按照往常一样,我是个懒人,只是使用的自动完成功能内置到Visual Studio 2008专业版它自动创建委托创作和它相关的方法。

I was registering to an event in my class, and as per usual I was lazy and just use the autocomplete feature built into Visual Studio 2008 Pro which auto creates the delegate creation and it's associated method.

public abstract class FooBase
{
    protected event EventHandler<MyValueChangedArgs> MyValueChanged;

    protected FooBase()
    {
        MyValueChanged +=
            new EventHandler<MyValueChangedArgs>(HandleMyValueChanged);
    }

    private void HandleMyValueChanged(object sender, MyValueChangedArgs e)
    {
        // Some handling logic
    }
}

通常我不认为在两次的Visual Studio一族的事件处理我,但后来我收到了推荐的重构!临去删除冗余委托创建。该建议的结果:

Usually I dont think twice when Visual Studio gens the event handler for me, but then I received a recommendation from Refactor! Pro to "Remove Redundant Delegate Creation". The recommendation results in:

public abstract class FooBase
{
    protected event EventHandler<MyValueChangedArgs> MyValueChanged;

    protected FooBase()
    {
        MyValueChanged += HandleMyValueChanged;
    }

    private void HandleMyValueChanged(object sender, MyValueChangedArgs e)
    {
        // Some handling logic
    }
}

在什么情况下是委托创建冗余的,如果是委托创作合适?

Under what circumstances is delegate creation redundant and when is delegate creation appropriate?

感谢。

推荐答案

我认为,重构!告诉你,行

I think that Refactor! tells you that the line

MyValueChanged += new EventHandler<MyValueChangedArgs>(HandleMyValueChanged);

可以缩短,编译器会推断出一个的事件处理程序创建和TEventArgs类型参数...

Can be shortened and the compiler will infer a event handler creation and the TEventArgs type argument...

在什么情况下是委托   创建冗余的,当是   委托创建合适?

Under what circumstances is delegate creation redundant and when is delegate creation appropriate?

在设计器生成的code ...

On designer-generated code...