代码之家  ›  专栏  ›  技术社区  ›  Dror Big McLargeHuge

C#互操作-验证对象存在

  •  1
  • Dror Big McLargeHuge  · 技术社区  · 17 年前

    我想在我的应用程序中使用COM对象。
    如何确保对象已在计算机中注册?

    我找到的唯一解决办法(也是 on SO )要在初始化过程中使用try-catch块:

    try {
        Foo.Bar COM_oObject = new Foo.Bar();
    } catch (Exception ee) {
        // Something went wrong during init of COM object
    }
    

    我可以用其他方法吗?
    我觉得通过期待和报告错误来处理错误是不对的,我宁愿知道我会失败并从一开始就避免它。

    4 回复  |  直到 9 年前
        1
  •  6
  •   Dan    16 年前

    您使用异常处理的方法是正确的:从您知道如何从中恢复的特定情况中优雅地失败。

    在这种情况下,使用try-catch没有问题,但至少可以更具体地捕获:ComException。

        2
  •  1
  •   Aamir    17 年前

        3
  •  1
  •   Sergey Mirvoda    17 年前

    如果您知道组件的ProgId。你可以试试这个把戏

    comType = Type.GetTypeFromProgID(progID,true/*throw on error*/);
    
        4
  •  0
  •   Daniel Earwicker    17 年前

    如果您经常这样做,并且希望有一个非异常抛出等价物,请尝试:

    public static class Catching<TException> where TException : Exception
    {
        public static bool Try<T>(Func<T> func, out T result)
        {
            try
            {
                result = func();
                return true;
            }
            catch (TException x) 
            {
                // log exception message (with call stacks 
                // and all InnerExceptions)
            }
    
            result = default(T);
            return false;
        }
    
        public static T Try<T>(Func<T> func, T defaultValue)
        {
            T result;
            if (Try(func, out result))
                return result;
    
            return defaultValue;
        }
    }
    

    现在你可以这样做了:

    Foo.Bar newObj;
    if (!Catching<ComException>.Try(() => new Foo.Bar(), out newObj))
    {
        // didn't work.
    }
    

    或者,如果在中存储了默认对象 defaultMyInterface 如果没有更好的方法,您可以使用来实现接口:

    IMyInterface i = Catching<ComException>.Try(() => new Foo.Bar() as IMyInterface,
                                                defaultMyInterface);
    

    您也可以在完全不同的场景中执行此操作:

    int queueSize = Catching<MyParsingException>
        .Try(() => Parse(optionStr, "QueueSize"), 5);
    

    Parse 抛出 MyParsingException , queueSize 将默认为 5 作语法分析

    这有助于避免中断代码流,还可以集中您的日志策略。