【问题标题】:COM component doesn't remain accessible in VBScriptCOM 组件在 VBScript 中无法访问
【发布时间】:2012-03-12 00:19:17
【问题描述】:

我有一个带有单个类 COMTest 的 C# 类库项目 (dll):

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;

namespace COMTest
{
    [Guid("45D639E4-FDDE-4b7b-A35F-FC19856DFF24")]
    [ComVisible(true)]
    public class Foo
    {
        public Foo()
        {
            Console.WriteLine("Constructing Foo");
        }

        private string mName = "FOO";
        public string Name
        {
            get { return mName; }
            set { mName = value; }
        }
    }
}

项目已注册 COM 互操作,并且程序集是 COM 可见的。目标框架是.Net 3.5,平台目标是x86。 .dll 使用 32 位 C:\Windows\Microsoft.NET\Framework\v2.0.50727\RegAsm.exe /codebase COMTest.dll 注册

我正在尝试从 VBScript(同样是 32 位,使用 C:\Windows\SysWOW64\cscript.exe test.vbs)访问此类,但在脚本中获取 Foo 的实例时似乎遇到了问题。我可以使用类;我只是无法保留对它的任何引用。

这是我的脚本:

Wscript.Echo "CreateObject(""ComTest.Foo"").Name Results: " + CreateObject("COMTest.Foo").Name
IF IsEmpty(CreateObject("COMTest.Foo")) THEN Wscript.Echo "CreateObject() is empty" ELSE Wscript.Echo "CreateObject() is NOT empty"

DIM foo : CreateObject("COMTest.Foo")
IF IsEmpty(foo) THEN Wscript.Echo "foo is empty" ELSE Wscript.Echo "foo is NOT empty"

这是输出:

Constructing Foo
CreateObject("ComTest.Foo").Name Results: FOO
Constructing Foo
CreateObject() is NOT empty
Constructing Foo
foo is empty

如您所见,CreateObject() 调用成功——我只是无法保留对返回对象的引用(在 foo 中)。

我觉得我错过了一些简单的东西。如何保留CreateObject()返回的对象?

【问题讨论】:

    标签: c# .net com vbscript


    【解决方案1】:

    您在第三行中使用的冒号实际上并没有做任何事情,它只是分隔了两个不同的语句。你的Dim foo : CreateObject("COMTest.Foo") 相当于:

    Dim foo
    CreateObject("COMTest.Foo")
    

    创建对象但实际上并未将其引用设置为任何变量。我会这样写:

    Dim foo
    Set foo = CreateObject("COMTest.Foo")
    WScript.Echo foo.Name
    

    【讨论】:

    • 我知道这一定很简单。谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-10-14
    • 2012-10-09
    • 2020-04-19
    • 2011-08-27
    • 2012-05-21
    • 2021-04-17
    • 2017-05-04
    相关资源
    最近更新 更多