实例化要在类库中使用的委托方法
本文关键字:方法 类库 实例化 | 更新日期: 2023-09-27 18:36:12
我正在构建一个电子邮件监控框架,我将用于少数用户,所以我正在构建一个类库来包装所有内容。我正在静态类中实例化配置(发送者、主题、上次接收等)。因此,我有这样的东西。
public static class MyConfig
{
public static int Sender { get; set; }
// and so on and so forth
public static void BuildMyConfig(string theSender, string theRecipient, ...)
{
Sender = theSender;
// yada yada yada...
}
}
public class Monitoring
{
public delegate void DoSomethingWithEmail(EmailContents theContents);
public void StartMonitoring() {
//When I get an email, I call the method
DoSomethingWithEmail(theEmailWeJustGot);
}
}
显然,在每种情况下,我们对电子邮件的处理方式将完全不同。我正在尝试的是实例化该委托。我该在哪里做?MyConfig 类,然后从那里调用它作为静态方法?监视类的实例?
应用程序看起来像...
public class SpecificMonitor
{
Monitoring.BuildMyConfig("foo@bar.com", "bar@foo.com", ...);
Monitoring m = new Monitoring();
m.StartMonitoring();
//But where do I build the delegate method???
}
到目前为止,我尝试过的每个选项都出现了编译错误。我还尝试使用接口重写方法而不是使用委托......但我认为授权是它所在的地方。
提前感谢!
与设计的其余部分一致(尽管我不一定同意设计很棒),您可以允许在配置类中设置回调
public static class MyConfig
{
public static string Sender { get; set; }
public static DoSomethingWithEmail EmailReceivedCallback { get; set; }
public static void BuildMyConfig(string theSender, string theRecipient,
DoSomethingWithEmail callback)
{
Sender = theSender;
EmailReceivedCallback = callback;
}
}
// Make sure you bring the delegate outside of the Monitoring class!
public delegate void DoSomethingWithEmail(string theContents);
当应用程序确认传入电子邮件时,您现在可以将电子邮件传递给分配给配置类的回调
public class Monitoring
{
public void StartMonitoring()
{
const string receivedEmail = "New Answer on your SO Question!";
//Invoke the callback assigned to the config class
MyConfig.EmailReceivedCallback(receivedEmail);
}
}
下面是一个用法示例
static void Main()
{
MyConfig.BuildMyConfig("...", "...", HandleEmail);
var monitoring = new Monitoring();
monitoring.StartMonitoring();
}
static void HandleEmail(string thecontents)
{
// Sample implementation
Console.WriteLine("Received Email: {0}",thecontents);
}
定义构造函数,以便当人们实例化Monitoring
对象时,他们必须定义委托:
public class Monitoring
{
public delegate void DoSomethingWithEmail(EmailContents theContents);
public Monitoring(Delegate DoSomethingWithEmail)
{
this.DoSomethingWithEmail = DoSomethingWithEmail;
}
public void StartMonitoring() {
//When I get an email, I call the method
DoSomethingWithEmail(theEmailWeJustGot);
}
}
然后在实例化每个Monitoring
时传入所需的delegate
:
Monitoring m = new Monitoring(delegate(EmailContents theContents)
{
/* Do stuff with theContents here */
});
m.StartMonitoring();