gpt4 book ai didi

c# - 实例化要在类库中使用的委托(delegate)方法

转载 作者:行者123 更新时间:2023-11-30 16:15:33 25 4
gpt4 key购买 nike

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

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);
}
}

显然,我们对电子邮件所做的处理在每种情况下都是完全不同的。我想要的是实例化该委托(delegate)。我会在哪里做那件事? 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???

}

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

提前致谢!

最佳答案

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

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);
}

关于c# - 实例化要在类库中使用的委托(delegate)方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19481357/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com