简体   繁体   English

C#中代表的实现

[英]Implementation of delegates in C#

I am trying to learn on how to use delegates efficiently in C# and I was just wondering if anyone can guide me through... The following is a sample implementation using delegates... All I am doing is just passing a value through a delegate from one class to another... Please tell me if this is the right way to implement... And also your suggestions... 我正在尝试学习如何在C#中有效地使用委托,我只是想知道是否有人可以指导我...以下是使用委托的示例实现...我所做的只是通过委托传递值从一个班级到另一个班级...请告诉我这是否是正确的实施方式......还有你的建议......

Also, please note that I have de-registered the delegate in : 此外,请注意我已取消注册代表:

void FrmSample_FormClosing(object sender, FormClosingEventArgs e)
{
     sampleObj.AssignValue -= new Sample.AssignValueDelegate(AssignValue);
}

Is this de-registration necessary? 这是否需要取消注册?

The following is the code that I have written.. 以下是我写的代码..

public partial class FrmSample : Form
{
    Sample sampleObj;

    public FrmSample()
    {
        InitializeComponent();

        this.Load += new EventHandler(FrmSample_Load);
        this.FormClosing += new FormClosingEventHandler(FrmSample_FormClosing);

        sampleObj = new Sample();
        sampleObj.AssignValue = new Sample.AssignValueDelegate(AssignValue);            
    }

    void FrmSample_FormClosing(object sender, FormClosingEventArgs e)
    {
        sampleObj.AssignValue -= new Sample.AssignValueDelegate(AssignValue);
    }

    void FrmSample_Load(object sender, EventArgs e)
    {
        sampleObj.LoadValue();
    }

    void AssignValue(string value)
    {
        MessageBox.Show(value);
    }
}

class Sample
{
    public delegate void AssignValueDelegate(string value);
    public AssignValueDelegate AssignValue;

    internal void LoadValue()
    {
        if (AssignValue != null)
        {
            AssignValue("This is a test message");
        }
    }
}

Pls provide your feedback on whether this is right... 请提供您对这是否正确的反馈...

Thanks, Ram 谢谢,拉姆

Explicitly unregistering event handlers is only necessary when the event reference keeps the object that contains the delegate target alive for too long. 仅当事件引用使包含委托目标的对象保持活动太长时,才需要显式取消注册事件处理程序。 In your case, the sampleObj will have a reference to the Form object. 在您的情况下,sampleObj将具有对Form对象的引用。 The C# syntax sugar hides this, the compiler actually generates this code: C#语法糖隐藏了这一点,编译器实际生成了这段代码:

sampleObj.AssignValue = new Sample.AssignValueDelegate( this , AssignValue); sampleObj.AssignValue = new Sample.AssignValueDelegate( this ,AssignValue);

Were the this argument initializes the Delegate.Target property and the AssignValue argument initializes the Delegate.Method property. 如果参数初始化Delegate.Target属性,则AssignValue参数初始化Delegate.Method属性。

Which means that as long as the sampleObj object stays referenced, the form object stays referenced too and won't be garbage collected. 这意味着只要sampleObj对象保持引用,表单对象也会保持引用,并且不会被垃圾回收。 However, in your case, the only object that has a reference to sampleObj is the form object itself. 但是,在您的情况下,唯一具有sampleObj引用的对象是表单对象本身。 The garbage collector has no trouble with circular references like this and will detect that there are no other references to either object. 垃圾回收器没有像这样的循环引用的麻烦,并且会检测到没有对这两个对象的其他引用。 And will collect them both at the same time. 并将同时收集它们。

There is one (uncommon) exception to this, you'll get in trouble with the sampleObj class generates events after the form is closed. 这有一个(不常见的)例外,你会遇到问题,sampleObj类在窗体关闭生成事件。 Which could happen if the event is triggered by something outside of the form, some hardware event for example. 如果事件由表单之外的某些事件触发,例如某些硬件事件,则可能发生这种情况。 That event could still run code in the form class. 该事件仍然可以在表单类中运行代码。 You usually notice this quickly, any attempt to reference a control in the form will throw an ObjectDisposed exception. 您通常会很快注意到这一点,任何在表单中引用控件的尝试都会抛出ObjectDisposed异常。

It's not necessary to deregister delegates. 没有必要取消注册代表。 You Sample obj lives in form scope and will be destroyed after form closing 您将示例obj存放在表单范围内,并在表单关闭后销毁

An Action delegate may be more appropriate in this case - it's a specific form of delegate that takes 1 - 3 parameters with no return value: 在这种情况下,Action委托可能更合适 - 它是一种特定形式的委托,它采用1-3个参数而没有返回值:

Uses of Action delegate in C# 在C#中使用Action委托

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM