对于一个项目,我正在尝试创建一个用 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
我收到(访问/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 的问题。
在这里阅读了一些内容后: http://jumbloid.blogspot.nl/2009/12/making-net-dll-com-visible.html 我发现我可以使用public interface
轻松调用我的 DLL 类。
所以我添加的是:
public interface ISendMail
{
void SendMail(string ToAddress, string Subject, string Body, string FromAddress, ref string[] attachments, string CCAddress = "", string BCCAddress = "");
}
我在我的类中添加了一个默认构造函数:public SendOPSMail() { }
我的类继承自创建的接口:public class SendOPSMail : ISendMail
现在我可以轻松地像这样调用 VBA 中的方法/类:
Dim test As OPS2Mail.SendOPSMail
Set test = New OPS2Mail.SendOPSMail