首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何检查程序集的类型是否为ComVisible

如何检查程序集的类型是否为ComVisible
EN

Stack Overflow用户
提问于 2015-03-22 11:15:26
回答 1查看 1.6K关注 0票数 5

我在为企业架构师写一个外接程序经理。

加载程序集(addin )时,我需要知道程序集中定义的哪些类型是COM可见的,因此我可以添加所需的注册表项来注册COM互操作。

到目前为止,我所拥有的是:

代码语言:javascript
复制
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
        }
    }            
}

这不起作用,因为类型似乎不包含ComVisibleAttribute。

有人知道如何确定组件中的哪个ExportedTypes是COM可见的吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-03-23 04:13:18

多亏了保罗的评论,我才弄明白了这一点。类型只有在与程序集默认值不同的情况下才具有ComVisibleAttribute。

因此,这个操作(对返回的Assembly.GetExportedTypes()类型之一进行调用)似乎可以做到这一点

代码语言:javascript
复制
/// <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;
}   
票数 7
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/29193669

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档