如何检查是否存在COM属性或方法,而不会产生异常?是否存在、属性、异常、方法

2023-09-07 03:03:32 作者:小娘不霸气怎显得你矫情ㄟ

我工作的一些遗留code,它创建一个包含属性和/或方法名字符串列表,然后尝试这些属性或方法适用于COM对象。该属性或方法的COM对象不能保证存在,它可以是一个属性或方法,我不知道是哪个。

I'm working on some legacy code that creates a list of strings containing property and/or method names and then attempts to apply those properties or methods to a COM object. The property or method for the COM object is not guaranteed to exist and it could be either a property or a method I don't know which.

目前,如果一个属性或方法不存在,它抓住了一个COM异常。这会导致性能不佳。我试图找到一种方法来检查,如果一个属性或方法存在于一个COM对象,而不会产生异常,这样我可以尝试使用它之前检查它的存在。

At the moment if a property or method doesn't exist it's caught as a COM exception. This results in poor performance. I am trying to find a way to check if a property or method exists in a COM object without generating an exception so that I can check for its existence before attempting to apply it.

使用的GetType返回类型为System.com_object。在System.com_object使用的getProperty因为这不能解决问题是确切的运行时类型不是它的衍生型。相反,我要InvokeMember如果成员不存在它创建一个例外。有没有人有这样做的更好的办法?

Using GetType returns type System.com_object. Using GetProperty on System.com_object doesn't work as this is the exact runtime type not the type it's derived from. Instead I have to InvokeMember which creates an exception if the member doesn't exist. Does anyone have a better way of doing this?

我在 .NET 3.5 目前的工作。迁移到.NET 4是不是在present一个选项,但我还是有兴趣的解决方案在.NET 4中,如果新的语言功能提供了解决问题的更好的方法。

I'm working in .NET 3.5 at the moment. Migration to .NET 4 is not an option at present but I'd still be interested in solutions in .NET 4 if the new language features provide a better way of solving the problem.

public static bool CheckIfComPropertyOrMethodExists<T1>(T1 objectToCheck, string propertyOrMethodName)
{
    if (CheckIfComPropertyExists(objectToCheck, propertyOrMethodName) == false & CheckIfComMethodExists(objectToCheck, propertyOrMethodName) == false) {
        return false;
    }
    {
        return true;
    }
}

public static bool CheckIfComPropertyExists<T1>(T1 objectToCheck, string propertyName)
{
    return objectToCheck.GetType().InvokeMember(propertyName, BindingFlags.GetProperty, null, objectToCheck, null) != null;
}

public static bool CheckIfComMethodExists<T1>(T1 objectToCheck, string methodName)
{
    return objectToCheck.GetType().GetMethod(methodName, BindingFlags.Public | BindingFlags.Instance) != null;
}

帮助文章至今

Helpful articles so far

How检查对象是否具有一定的方法/属性?

Calling对IDispatch的COM接口从C#成员

http://msdn.microsoft.com/en-us/library/ aa909091.aspx

Implementing的IDispatch在C#

http://msdn.microsoft.com/en-us/magazine/ dd347981.aspx

的http://blogs.msdn.com/b/lucian/archive/2008/10/06/reflection-on-com-objects.aspx

推荐答案

最有可能的COM类还实现了IDispatch接口。然后,您可以使用它的GetIDsOfNames来检查成员是否在类存在。

Most probably the COM class implements also the IDispatch interface. You could then use its GetIDsOfNames to check whether a member exists in the class.

下面有人从C#调用它:

Here someone calls it from C#:

Calling对IDispatch的COM接口从C#成员