3

我正在构建一个电子邮件监控框架,我将为少数用户使用,所以我正在构建一个类库来包装所有内容。我正在实例化配置(发件人、主题、最后收到的. ..) 在静态类中。因此,我有这样的事情。

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???

}

到目前为止,我尝试过的每个选项都出现编译错误。我也尝试过重写方法而不是使用委托,使用接口......但我认为委托就是它所在的地方。

提前致谢!

4

2 回答 2

2

与您的其余设计一致(尽管我不一定同意该设计很棒),您可以允许在配置类中设置回调

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);
}
于 2013-10-20T19:01:34.947 回答
1

定义构造函数,这样当人们实例化一个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);
    }
}

然后在实例化 each 时传入delegate你想要的Monitoring

Monitoring m = new Monitoring(delegate(EmailContents theContents) 
{ 
    /* Do stuff with theContents here */
});
m.StartMonitoring();
于 2013-10-20T18:58:58.993 回答