在 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.
有没有人管理过这个,或者有其他想法?
最佳答案
您可以使用某些方法和属性,但不是全部。
以下工作,但从您使用 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。
关于.net - 是否可以在 VBScript 中获取 .Net 字符串对象实例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10582696/