您有两个主要选项来实现此目的,或者要求控件的用户提供一个上传方法,当单击“上传”按钮时由您的控件调用该方法,或者您可以要求控件是子类,并且Upload
方法实施的。
方法 1 - 提供要在上传时调用的委托:
public partial class MyControl
{
// Define a delegate that specifies the parameters that will be passed to the user-provided Upload method
public delegate void DoUploadDelegate(... parameters ...);
private readonly DoUploadDelegate _uploadDelegate;
public MyControl(DoUploadDelegate uploadDelegate)
{
if (uploadDelegate == null)
{
throw new ArgumentException("Upload delegate must not be null", "uploadDelegate");
}
_uploadDelegate = uploadDelegate;
InitializeComponent();
}
// ...
// Upload button Click event handler
public void UploadButtonClicked(object sender, EventArgs e)
{
// Call the user-provided upload handler delegate with the appropriate arguments
_uploadDelegate(...);
}
}
方法 2 - 要求覆盖上传方法:
public abstract partial class MyControl
{
private readonly DoUploadDelegate _uploadDelegate;
protected MyControl()
{
InitializeComponent();
}
// ...
// The method that users of the control will need to implement
protected abstract void DoUpload(... parameters ...);
// Upload button Click event handler
public void UploadButtonClicked(object sender, EventArgs e)
{
// Call the overridden upload handler with the appropriate arguments
DoUpload(...);
}
}
对于后一种选项,用户需要先对控件进行子类化,然后才能使用它,如下所示:
public class MyConcreteControl : MyControl
{
protected override void DoUpload(... parameters ...)
{
// User implements their own upload logic here...
}
}