公开IDispatchEx
适用于 JavaScript,但我认为 VBA 不会使用它。AFAIK,VBA 依赖于IDispatch
后期绑定。此外,C#dynamic
非常适合IDispatch
在 .NET 端使用基于 COM 的对象,但反之则不然。出于某种原因(.NET 设计人员决定?),默认情况下 和 的动态属性和方法ExpandoObject
不会DynamicObject
暴露给 COM。
幸运的是,有一种方法可以覆盖它:通过实现IReflect接口。有关实现细节,请参阅这篇出色的博客文章。我自己看过将 C# 匿名类的属性暴露给 COM,最后使用IReflect
. 这就是您可以向 COM 公开动态方法和属性的方式。形象地说,IReflect
暴露给 COM 作为IDispatch
.
附带说明一下,IExpando为IDispatchEx
.
[更新]下面是一个原型实现,它将DynamicComponent
VBScript 的实例公开给在WebBrowser
. 它适用于 VBScript,也适用于 VBA。虽然,我怀疑 VBA 自动完成是否会起作用,或者有一种简单的方法可以实现这种功能。AFAIU,VBA 自动完成依赖于 COM 类型库(可通过 获得IDispatch::GetTypeInfo
),但我认为 .NET 互操作引擎在实现时不会生成动态类型库IDispatch
(IReflect
我可能错了)。此外,此实现对于按名称查找的方法区分大小写,应进行调整,因为 VB 不区分大小写。
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Windows.Forms;
namespace WebBrowserApp
{
// https://stackoverflow.com/a/19067386/1768303
public partial class MainForm : Form
{
WebBrowser wb;
public MainForm()
{
InitializeComponent();
this.wb = new WebBrowser();
this.wb.Dock = DockStyle.Fill;
this.Controls.Add(this.wb);
this.wb.Visible = true;
var dynamicComponent = new DynamicComponent();
// make dynamicComponent available to VBScript
this.wb.ObjectForScripting = dynamicComponent;
// add a dynamic method "Convert"
dynamicComponent.SetMethod("Convert", new Func<int, string>((a) =>
{
MessageBox.Show("Convert called: " + a.ToString());
return a.ToString();
}));
this.Load += (s, e) =>
{
this.wb.DocumentText =
"<script type='text/vbscript'>\n" +
"Sub OnLoadHandler\n" +
" alert window.external.Convert(42)\n" +
"End Sub\n" +
"window.onload = GetRef(\"OnLoadHandler\")\n" +
"</script>";
};
}
}
#region DynamicComponent
[ComVisible(true), ClassInterface(ClassInterfaceType.None)]
public class DynamicComponent : System.Reflection.IReflect
{
readonly Dictionary<string, Delegate> _methods = new Dictionary<string, Delegate>();
public void SetMethod(string name, Delegate value)
{
_methods[name] = value;
}
static Exception NotImplemented()
{
var method = new StackTrace(true).GetFrame(1).GetMethod().Name;
Debug.Assert(false, method);
return new NotImplementedException(method);
}
#region IReflect
// IReflect
public FieldInfo GetField(string name, BindingFlags bindingAttr)
{
throw NotImplemented();
}
public FieldInfo[] GetFields(BindingFlags bindingAttr)
{
return new FieldInfo[0];
}
public MemberInfo[] GetMember(string name, BindingFlags bindingAttr)
{
throw NotImplemented();
}
public MemberInfo[] GetMembers(BindingFlags bindingAttr)
{
return new MemberInfo[0];
}
public MethodInfo GetMethod(string name, BindingFlags bindingAttr)
{
throw NotImplemented();
}
public MethodInfo GetMethod(string name, BindingFlags bindingAttr, Binder binder, Type[] types, ParameterModifier[] modifiers)
{
throw NotImplemented();
}
public MethodInfo[] GetMethods(BindingFlags bindingAttr)
{
return _methods.Keys.Select(name => new DynamicMethodInfo(name, _methods[name].Method)).ToArray();
}
public PropertyInfo[] GetProperties(BindingFlags bindingAttr)
{
return new PropertyInfo[0];
}
public PropertyInfo GetProperty(string name, BindingFlags bindingAttr, Binder binder, Type returnType, Type[] types, ParameterModifier[] modifiers)
{
throw NotImplemented();
}
public PropertyInfo GetProperty(string name, BindingFlags bindingAttr)
{
throw NotImplemented();
}
public object InvokeMember(string name, BindingFlags invokeAttr, Binder binder, object target, object[] args, ParameterModifier[] modifiers, System.Globalization.CultureInfo culture, string[] namedParameters)
{
if (target == this && invokeAttr.HasFlag(BindingFlags.InvokeMethod))
{
Delegate method;
if (!_methods.TryGetValue(name, out method))
throw new MissingMethodException();
return method.DynamicInvoke(args);
}
throw new ArgumentException();
}
public Type UnderlyingSystemType
{
get { throw NotImplemented(); }
}
#endregion
#region DynamicMethodInfo
// DynamicPropertyInfo
class DynamicMethodInfo : System.Reflection.MethodInfo
{
string _name;
MethodInfo _mi;
public DynamicMethodInfo(string name, MethodInfo mi)
: base()
{
_name = name;
_mi = mi;
}
public override MethodInfo GetBaseDefinition()
{
return _mi.GetBaseDefinition();
}
public override ICustomAttributeProvider ReturnTypeCustomAttributes
{
get { return _mi.ReturnTypeCustomAttributes; }
}
public override MethodAttributes Attributes
{
get { return _mi.Attributes; }
}
public override MethodImplAttributes GetMethodImplementationFlags()
{
return _mi.GetMethodImplementationFlags();
}
public override ParameterInfo[] GetParameters()
{
return _mi.GetParameters();
}
public override object Invoke(object obj, BindingFlags invokeAttr, Binder binder, object[] parameters, System.Globalization.CultureInfo culture)
{
return _mi.Invoke(obj, invokeAttr, binder, parameters, culture);
}
public override RuntimeMethodHandle MethodHandle
{
get { return _mi.MethodHandle; }
}
public override Type DeclaringType
{
get { return _mi.DeclaringType; }
}
public override object[] GetCustomAttributes(Type attributeType, bool inherit)
{
return _mi.GetCustomAttributes(attributeType, inherit);
}
public override object[] GetCustomAttributes(bool inherit)
{
return _mi.GetCustomAttributes(inherit);
}
public override bool IsDefined(Type attributeType, bool inherit)
{
return _mi.IsDefined(attributeType, inherit);
}
public override string Name
{
get { return _name; }
}
public override Type ReflectedType
{
get { return _mi.ReflectedType; }
}
}
#endregion
}
#endregion
}