【发布时间】:2016-04-26 14:07:49
【问题描述】:
对于一个项目,我正在尝试创建一个用 C# 创建并在 Access 中使用的自定义库。为此,我执行了以下操作:
- 在 Visual Studio 2012 中创建了一个类库,
- 使程序集 COM 可见(在项目属性 --> 程序集信息中),
- 已注册 COM 互操作项目,
-
using System.Runtime.InteropServices;在我的班级中。
DLL 的目的是通过 SMTP 处理/发送具有多个地址、附件等的邮件。为此,我创建了以下内容:
[Serializable(), ClassInterface(ClassInterfaceType.AutoDual), ComVisible(true)]
public class SendOPSMail
{
public void SendMail(string ToAddress, string Subject, string Body, string FromAddress, ref string[] attachments, string CCAddress = "", string BCCAddress = "")
{
//Check if attachment is null or not else assign empty value
attachments = attachments ?? new string[0]; //after research it seems that I cant assign a NULL array in VBA/DLL and need to be passed by ref - so this can be deleted
using (var msg = new MailMessage())
using (var client = new SmtpClient("spamfilter.mySpamFilter.com", 587))
{
msg.IsBodyHtml = true;
msg.BodyEncoding = System.Text.Encoding.UTF8;
msg.SubjectEncoding = System.Text.Encoding.UTF8;
if (!string.IsNullOrEmpty(FromAddress))
{
msg.From = new MailAddress(FromAddress);
}
string[] splitTO = ToAddress.Split(delimiterChars);
foreach (var TO in splitTO)
{
msg.To.Add(new MailAddress(TO));
}
//handle attachments
foreach (string value in bijlagen)
{
msg.Attachments.Add(new Attachment(value));
}
//set the remaining required fields
msg.Body = Body;
msg.Subject = Subject;
//Send mail
client.Send(msg);
}
}
}
我将 DLL 包含在我的 Access 引用中,一切顺利。虽然当我尝试如下称呼我的班级时:
Dim test As OPS2Mail.SendOPSMail
Set test = New OPS2Mail.SendOPSMail
test.SendMail "some@email.com", "Test", "<b>Test</b>", "some@email.com", AttachmentArray
我收到 (Access/VBA) 错误 438, the property or method is not supported for this object.
因此,经过研究,我发现了一篇文章,他们说我必须在 DLL 中创建一个主类,该类使用函数 (SendOPSMail) 调用该类,然后在 VBA 中我首先初始化该主类以调用另一个类。所以在我添加的DLL代码中:
public class MainOPSMail
{
public SendOPSMail GetSendOPSMail()
{
return new SendOPSMail();
}
}
在 VBA/Access 中我将其更改为:
Dim testMain As OPS2Mail.MainOPSMail
Set testMain = New OPS2Mail.MainOPSMail
Dim test as OPS2Mail.SendOPSMail
set test = testMain.GetSendOPSMail
test.SendMail "some@email.com", "Test", "<b>Test</b>", "some@email.com", AttachmentArray
这似乎可行,但为什么调用会如此麻烦?有没有办法让它更简单?就像我创建一个类一样,将其设为com-visible,然后用一个简单的Dim 和set 调用它(或者甚至不用设置?)
抱歉,如果帖子包含大量愚蠢的问题,但我对此有点陌生,尤其是 DLL。
【问题讨论】:
-
我想如果这个类是静态的,你可能刚刚能够调用它
-
我自己发现的。可以使用界面来完成。会尽可能回答我的问题。