我有一些C#代码我正在尝试转换为VB.NET。我在每个项目中都引用了一些外部依赖项。 C#行是
TWriteFileCommand writeFile = (TWriteFileCommand)CommunicationLink.CreateCommand(TOPKernel.TCommand.CommandType.WriteFile);
我真的不明白在该等陈述中等号后的拟合中的TWriteFileCommand是什么。当我尝试在VB.NET中执行此操作时,我不断收到错误,因为我无法获得对CreateCommand函数的引用。我得到的最接近的是:
Dim MyAppBase As OPSupport.App.AppBase
Dim writeFile As TWriteFileCommand
writeFile = MyAppBase.CommunicationLink.CreateCommand(TOPKernel.TCommand.CommandType.WriteFile)
但是,我在@ MyAppBase等号后面有一个绿色下划线标记错误“在赋值变量之前使用变量MyAppBase。在运行时可能会产生空引用异常。”
我错过了什么?为什么在C#代码中实例很好,在VB.NET中获取等效实例需要什么?请指教。
答案 0 :(得分:4)
这是演员阵容;如果CreateCommand
返回object
,CommandBase
或类似内容,则会对TWriteFileCommand
进行类型检查。
如果您编译了C#代码 - 可以使用反射器进行翻译吗?这会在下拉菜单中显示C#和等效的VB。
我不确定MyAppBase
正在做什么;在C#中不存在 - 你为什么要把它添加到VB?
编辑我不“做”VB,但我在反射器中查找了它; (Foo)bar
变为DirectCast(bar, Foo)
。
答案 1 :(得分:3)
看起来CreateCommand
是CommunicationLink
类型中的静态方法。要么是,要么是名为CommunicationLink
的属性,并且其类型具有CreateCommand
方法。
=之后括号中的位是强制转换。使用CType
或DirectCast
在VB.NET中执行此操作。
答案 2 :(得分:1)
()
是C#从一种类型转换为另一种类型的方式之一。 VB等价物是CType()
。
答案 3 :(得分:1)
直接等效于:
Dim writeFile As TWriteFileCommand
writeFile = DirectCast(CommunicationLink.CreateCommand(TOPKernel.TCommand.CommandType.WriteFile), TWriteFileCommand)
答案 4 :(得分:0)
在C#代码中,通信链接变量在和实例化中声明了什么?您需要确保VB代码对该对象使用相同的源。
答案 5 :(得分:0)
我真的能看到Dim MyAppBase As OPSupport.App.AppBase
来自哪里。
就(TWriteFileCommand)
而言,这是一个类型转换。 DirectCast
具有(几乎?)相同的功能。
答案 6 :(得分:0)
这是因为您没有为MyAppBase分配变量值: - )
Dim MyAppBase As OPSupport.App.AppBase = new OPSupport.App.AppBase()
Dim writeFile As TWriteFileCommand
writeFile = MyAppBase.CommunicationLink.CreateCommand(TOPKernel.TCommand.CommandType.WriteFile)