我正在创建一个 COM 可见 dll,并且尝试重载一个方法。
基本上这段代码是:
[ComVisible(true)]
[ProgId("TAF.TextLog")]
[Guid("af3f89ed-4732-4367-a222-2a95b8b75659")]
public class TextLog
{
String _logFilePath;
public TextLog()
{
}
[ComVisible(true)]
public void Create(string filePath)
{
String path = Path.GetDirectoryName(filePath);
if (Directory.Exists(path))
{
_logFilePath = filePath;
}
[ComVisible(true)]
public void Write(string message)
{
WriteMessage(null, message, AlertMsg.MsgTypes.Info);
}
[ComVisible(true)]
public void Write(string title, string message, AlertMsg.MsgTypes messageType)
{
WriteMessage(title, message, messageType);
}
private void WriteMessage(string title, string message, AlertMsg.MsgTypes messageType)
{
using (StreamWriter file = new StreamWriter(_logFilePath, true))
{
if (title == null)
file.WriteLine(String.Format("{0:yyyy-MM-dd HH:mm:ss}\t{1}", DateTime.Now, message));
else
file.WriteLine(String.Format("{0:yyyy-MM-dd HH:mm:ss}\t{1}\t{2}\t{3}", DateTime.Now, title, message, messageType));
}
}
}
但是看起来这是不可能的。如果我从调用程序(顺便说一下,这是一个非常简单的 VBSCript)调用 .Write,我会收到一条错误消息,指出我的参数不正确。
这是调用 VBscript 代码:
Set myObj = CreateObject("TAF.TextLog")
myObj.Create("C:\temp\textlog.txt")
myObj.Write "title", "test message 1", 1
如果我在 dll 中只有一个 .Write 方法,它就可以正常工作。有人可以告诉我在 dll 中是否可以进行这样的重载吗?
最佳答案
COM 不支持成员重载,每个名称必须是唯一的。 IDispatch::GetIDsOfNames() 不可避免的副作用。脚本解释器用于将脚本代码中使用的“Write”转换为 dispid 的函数。该方法仍然存在,只是没有办法让 GetIDsOfNames() 返回其 dispid。类型库导出器通过重命名重载方法解决了这个问题,它将是Write_2()
。
没有解决方法,当您使用后期绑定(bind)时,您必须避免重载。
关于c# - 重载com可见dll中的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25650039/