将Action <t>存储在单个集合中以供以后使用

时间:2015-08-31 08:28:07

标签: c# generics

我试图在内存中保存@Component public class MailSenderService { @Autowired JavaMailSender javaMailSender; @Value("${reports.mailSender.clientEmail}") private String clientEmail; public void sendMessage() { MimeMessage mimeMessage = javaMailSender.createMimeMessage(); FileSystemResource file = new FileSystemResource(new File("c:\\simple.jpg")); try { mimeMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(clientEmail)); mimeMessage.setFrom("xyz@gmail.com"); mimeMessage.setText( "Hi"); MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true); helper.addAttachment(file.getFilename(), file); } catch (MessagingException e) { e.printStackTrace(); } try { this.javaMailSender.send(mimeMessage); } catch (MailException ex) { // simply log it and go on... System.err.println(ex.getMessage()); } } } 类型的引用集合,其中T是变量类型

我找到了Action<T>的解决方案,但我不想使用动态解决方案

dynamic

有没有人知道更好的处理方法? 提前谢谢。

1 个答案:

答案 0 :(得分:10)

Action<T>Delegate,因此......

public class MessageSubscriptor:IMessageSubscriptorPool
{
    private readonly Dictionary<Type, Delegate> _callbacks = new Dictionary<Type, Delegate>();

    public void Subscribe<T>(Action<T> callback) where T :IMessage
    {
        _callbacks.Add(typeof(T), callback);
    }
}

然后,假设你要调用一个,你可以简单地执行一个演员:

public void Invoke<T>(T message) where T :IMessage
{
    Delegate callback;
    if (_callbacks.TryGetValue(typeof(T), out callback))
        ((Action<T>)callback).Invoke(message);
}