【问题标题】:How do I check a property of a COM object for a null value in VB6?如何在 VB6 中检查 COM 对象的属性是否为空值?
【发布时间】:2014-01-03 11:18:51
【问题描述】:

我正在为 VB6 旧版应用程序开发一个扩展。

我们用 C# 开发了一个扩展,它通过 COM 暴露给 VB6。 C# 解决方案中的一种方法返回具有多个属性的对象,其中一些属性本身是项目中定义的类的实例(不是实际的 sn-p;不幸的是,我不允许发布原始代码):

public class CustomType
{
   ...
}

public class ComAdapter
{
  public CustomType ExampleProperty 
  { 
    get { ... } // edited: this was not an auto-property and causing an exception
  }

  ... (more properties and some logic)
}

在 Vb6 中,我们接收 ComAdapter 类的实例。在某些情况下,属性 Instance 可以为 null - 这是有意的。这应该会在旧版应用中触发不同的行为。问题是:如何检查 ExampleProperty 属性是否为空?

我已经尝试了以下所有方法:

Dim oAdapter as ComAdapter
... (code to retrieve instance ComAdapter)

If oAdapter.ExampleProperty Is Nothing Then (...)
If oAdapter.ExampleProperty Is Null Then (...)
If oAdapter.ExampleProperty Is Empty Then (...)
If IsNothing(oAdapter.ExampleProperty) Then (...)
If IsNull(oAdapter.ExampleProperty) Then (...)
If IsEmpty(oAdapter.ExampleProperty) Then (...)

全部失败。在所有情况下,我都会得到“对象引用未设置为对象的实例”。我猜这与我正在尝试检查属性有关,但我不知道如何解决它。

编辑:我检查了 oAdapter 是否设置正确。除了我试图检查哪些属性实际上可以访问之外,还有其他几个属性,因此 oAdapter 似乎不太可能是问题。

【问题讨论】:

  • 它抱怨的是 oAdapter,而不是属性。

标签: com vb6


【解决方案1】:

第一个是正确的语法。

If oAdapter.ExampleProperty Is Nothing Then (...)

如果您收到“未将对象引用设置为对象的实例”,oAdapterNothing (null) 或 ExampleProperty 实际上不是您建议的自动参数。

【讨论】:

  • 我检查了 oAdapter;它不是什么都没有(还有其他几个可以检查的属性) - 我将重新检查我的示例,看看我是否在简化代码时遗漏了一些东西。
  • 您关于 ExampleProperty 不是自动属性的建议实际上帮助了我 - 在完整的代码中,它确实不是自动属性;返回值时发生错误。
【解决方案2】:

也许可以这样尝试(显然,没有你的代码我无法测试):

Dim oAdapter as ComAdapter
... (code to retrieve instance ComAdapter)

Dim oCustomType as CustomType

Set oCustomType = oAdapter.ExampleProperty

if oCustomType Is Nothing Then (...)

【讨论】:

  • 我试过了 - 我仍然得到同样的错误,但现在在 Set oCustomType = oAdapter.ExampleProperty 指令上。
猜你喜欢
  • 2014-08-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-05-06
  • 2020-08-08
  • 2020-09-21
  • 1970-01-01
相关资源
最近更新 更多