是否有可能在VBScript中获得.Net字符串对象实例?

时间:2012-05-14 11:44:35

标签: .net string com vbscript

在VBScript中,您可以使用COM自动化使用某些.net类。当您想要使用动态数组,列表,队列等时,这会派上用场。

如果我可以使用字符串作为对象,那将是很好的,所以我可以使用它all fancy string stuff,但每当我从另一个对象传递一个字符串时,它被VBScript视为字符串而不是字符串对象:

Set s = CreateObject("System.Text.StringBuilder")
s.Append_3 "I love deadlines. I like the whooshing sound they make as they fly by."

' This gives me the literal string
MsgBox s.ToString
text = s.ToString

' But unfortunately this won't work
MsgBox s.ToString.Length
Set stringRef = s.ToString

同时将字符串创建为COM对象也不起作用:

Set s = CreateObject("System.String")      ' Nope.

是否有人管理过这个问题,或者对此有其他想法?

2 个答案:

答案 0 :(得分:7)

您可以使用某些方法和属性,而不是全部。 以下工作,但从您使用toString的那一刻起,您就有了一个行为相同的vbscript变量。

Set s = CreateObject("System.Text.StringBuilder")
s.Append_3 "I love deadlines. I like the whooshing sound they make as they fly by."
s.Append_3 "and the rest."
wscript.echo s.Length
wscript.echo s.Capacity
wscript.echo chr(s.chars(0))
wscript.echo s.Replace("t", "d").Replace("l", "k").toString

给出

83
140
I
I kove deadkines. I kike dhe whooshing sound dhey make as dhey fky by.and dhe resd.

但是,例如以下内容不起作用,尽管它是一种stringbuilder http://msdn.microsoft.com/en-us/library/system.text.stringbuilder_methods.aspx的方法 不要问我为什么

s.Insert 1, "insert this"

s.Insert_2 7, "insert this"

有效吗

我也在Ruby中编程,你也可以在这里使用这些对象,这就是同样的行为。对于某些对象,我可以枚举属性或方法,例如Excel

require 'win32ole'
excel = WIN32OLE.new('Excel.Application')
properties = excel.ole_get_methods
properties.each do |property|
  p property.to_s
end

给出了很长的列表,如

"Application"
"Creator"
"Parent"
"ActiveCell"
"ActiveChart"
"ActiveDialog"
"ActiveMenuBar"
"ActivePrinter"
"ActiveSheet"
"ActiveWindow"
"ActiveWorkbook"
etc etc

但对于System.Text.Stringbuilder来说并非如此,我想这是由于程序员将他的方法和属性暴露给外部的方式。

可悲的是,我认为不可能在vbscript中直接使用System.String。

答案 1 :(得分:0)

你试过吗? Msgbox len(s.ToString) 或者只是MsgBox(s.Length)

或者您可以创建自己的.Net类并将其公开给com,它将充当您要公开的静态字符串函数的包装器...