实例化要在类库中使用的委托方法

时间:2013-10-20 18:45:46

标签: c# .net delegates class-library

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

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类然后从那里作为静态方法调用它? Monitoring类的实例?

应用程序看起来像......

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

}

到目前为止,我已尝试过每个选项都会编译错误。我也试过覆盖一个方法,而不是使用委托,使用接口...但我认为委托就在它的位置。

提前致谢!

2 个答案:

答案 0 :(得分: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);
}

答案 1 :(得分: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);
    }
}

然后在实例化每个delegate时传入您想要的Monitoring

Monitoring m = new Monitoring(delegate(EmailContents theContents) 
{ 
    /* Do stuff with theContents here */
});
m.StartMonitoring();