开发者

C# how to dynamically cast an object?

I am building a helper object that has a property called Mailer. In reality Mailer can be either a System.Net.Mail.MailMessage or a Mono.System.Net.Mail.MailMessage. So I would preferably only want 1 declaration of mailer.

For example I don't want:

private Mono.Mailing.MailMessage MonoMessage = new Mono.Mailing.MailMessage();
private System.Net.Mail.MailMessage MailMessage = new System.Net.Mail.MailMessage();

I would prefer

object mailer;

Then in constructor

switch (software)
            {
                case EnunInternalMailingSoftware.dotnet:
                    this.mailer = new System.Net.Mail.MailMessage();
                    break;
                case EnunInternalMailingSoftware.mono:
                    this.mailer = new Mono.Mailing.MailMessage(); 
                开发者_运维问答    break;
            }

The problem is that mailer has no properties at design time. So I can't compile my code.

How can this be fixed, am I taking the right approach. Thanks in advance


You should use the adapter pattern for this: http://en.wikipedia.org/wiki/Adapter_pattern

Define an interface that covers the methods you need (e.g. SendMail()) and then write a simple adapter class for each MailMessage object that implements the interface and delegates to the correct methods on the specific MailMessage class.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜