Generic Proxy Class
This may not the worded quite right but here goes anyway.
If I have the following statements;
DocumentMerger<EmailMerge> mailMerge = new DocumentMerger<EmailMerge>();
List<MailMessage> mailMessages = mailMerge.Process();
DocumentMerger<SmsMerge> mailMerge = new DocumentMerger<SmsMerge>();
List<SmsMessage> smsMessages = mailMerge.Process();
How can I create a generic clas开发者_运维知识库s that takes a type as its generic such as EmailMerge
and returns either a list of MailMessage or SmsMessage objects?
I have a class called DocumentMerger which creates my object EmailMerge or SmsMerge.
I now need both of them to expose a Process method which returns its own unique list of objects such as List<MaileMessage>
or List<SmsMessage>
I suspect proxies might be the go here but can't work out the code.
Please re-title this question if you think it's not clear enough.
An interface could solve your problem..
public interface IDocumentMerger
{
}
public interface IOutputType
{
}
public class MailMessage : IOutputType
{
}
public class EmailMerge : IDocumentMerger
{
}
public class SmsMerge : IDocumentMerger
{
}
public class DocumentMerger<T> where T : IDocumentMerger
{
public List<IOutputType> Process()
{
IOutputType result = null;
if (typeof(T) == EmailMerge)
{
result = new MailMessage();
}
// etc..
// do stuff..
return result;
}
}
And you'd use it like this:
var documentMerger = new DocumentMerger<EmailMerge>();
var emailMerge = documentMerger.Process();
emailMerge is of type List<MailMessage>
...
I hope I understood your question correctly.. Code is untested, but should be correct.. Or really close to it :)
Ian
edit -- looks like I misread your requirements.. it's an easy fix though, see edit.
精彩评论