Gee*_*ens 5 .net c# com interop com-interop
我正在为Enterprise Architect编写一个加载项管理器.
当加载程序集(addin dll)时,我需要知道程序集中定义的哪些类型是COM可见的,所以我可以添加所需的注册表项来为COM interop注册它.
这是我到目前为止所拥有的:
public EAAddin(string fileName):base()
{
//load the dll
this.addinDLL = Assembly.LoadFrom(fileName);
//register the COM visible classes
this.registerClasses(this.addinDLL);
//load referenced dll's
foreach (AssemblyName reference in this.addinDLL.GetReferencedAssemblies())
{
if (System.IO.File.Exists(
System.IO.Path.GetDirectoryName(this.addinDLL.Location) +
@"\" + reference.Name + ".dll"))
{
Assembly referencedAssembly = System.Reflection.Assembly.LoadFrom(System.IO.Path.GetDirectoryName(this.addinDLL.Location) + @"\" + reference.Name + ".dll");
//register the COM visible classes for the registered assembly
this.registerClasses(referencedAssembly);
// ... more code ...
private void registerClasses (Assembly assembly)
{
foreach (Type type in assembly.GetExportedTypes())
{
register(type, assembly);
}
}
private void register(Type type, Assembly assembly)
{
var attributes = type.GetCustomAttributes(typeof(ComVisibleAttribute),false);
if (attributes.Length > 0)
{
ComVisibleAttribute comvisible = (ComVisibleAttribute)attributes[0];
if (comvisible.Value == true)
{
//TODO add registry keys here
}
}
}
Run Code Online (Sandbox Code Playgroud)
这不起作用,因为类型似乎不包含ComVisibleAttribute.
任何人都知道如何弄清楚程序集中的哪些ExportedTypes是COM可见的?
感谢Paulo的评论我能够弄明白.如果类型与Assembly默认值不同,则该类型仅具有ComVisibleAttribute.
因此,这个操作(在返回的类型之一上调用Assembly.GetExportedTypes())似乎可以解决问题
/// <summary>
/// Check if the given type is ComVisible
/// </summary>
/// <param name="type">the type to check</param>
/// <returns>whether or not the given type is ComVisible</returns>
private bool isComVisible(Type type)
{
bool comVisible = true;
//first check if the type has ComVisible defined for itself
var typeAttributes = type.GetCustomAttributes(typeof(ComVisibleAttribute),false);
if (typeAttributes.Length > 0)
{
comVisible = ((ComVisibleAttribute)typeAttributes[0]).Value;
}
else
{
//no specific ComVisible attribute defined, return the default for the assembly
var assemblyAttributes = type.Assembly.GetCustomAttributes(typeof(ComVisibleAttribute),false);
if (assemblyAttributes.Length > 0)
{
comVisible = ((ComVisibleAttribute)assemblyAttributes[0]).Value;
}
}
return comVisible;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1107 次 |
| 最近记录: |