简体   繁体   English

试图将VB代码转换为C#但发生错误

[英]Tried to convert VB code to C# but error occurred

I did convert the VB code to below C# code, but error occurred. 我确实将VB代码转换为以下C#代码,但是发生了错误。 I am getting error in Strings.InStr and Strings.Mid . 我在Strings.InStrStrings.Mid遇到错误。

    sHeadingNm = ActiveDocument.Styles(wdStyleHeading1).NameLocal;  
if (!string.IsNullOrEmpty(sHeadingNm)) {  
    nPos = Strings.InStr(1, sHeadingNm, "1");  
    if (nPos > 0)  
        sHeadingNm = Strings.Mid(sHeadingNm, 1, nPos - 1);  
}  

//=======================================================  
//Service provided by Telerik (www.telerik.com)  
//Conversion powered by NRefactory.  
//Twitter: @telerik  
//Facebook: facebook.com/telerik  
//=======================================================  

Please help me... 请帮我...

C# equivalents of method you've used: 您使用过的C#等效方法:

Strings.InStr has equivalent of String.IndexOf Strings.InStr具有String.IndexOf的等效项

Strings.Mid has equivalent of String.Substring Strings.Mid具有String.Substring的等效

Your problem must be that Strings.InStr and Strings.Mid are not standard methods in C#, but in VB.net. 您的问题必须是Strings.InStrStrings.Mid在C#中不是标准方法,而在VB.net中。 You should add probably using Microsoft.VisualBasic in order to use them, although i'd recommend to use C# equivalent methods. 您应该添加using Microsoft.VisualBasic才能使用它们,尽管我建议使用C#等效方法。

Better stated, you let the Telerik converter convert the code. 更好地说,您让Telerik转换器转换代码。 Code converters can't safely assume that library and function calls which exist in one language do not exist in the other; 代码转换器不能安全地假定一种语言中存在的库和函数调用不存在另一种语言中; for all they know, your destination code has a custom library that mimics the behavior of functions only present in the source language. 就他们所知,目标代码具有一个自定义库,该库模仿仅源语言中存在的功能的行为。 Additionally, most functions in VB that are VB-only are 1-based, not 0-based as in the rest of .Net. 此外,VB中大多数仅VB的功能都是基于1的,而不是.Net其余部分中的基于0的功能。

For this reason, you don't get an automatic conversion of Strings.InStr to String.IndexOf . 因此,您不会自动将Strings.InStr转换为String.IndexOf You also won't see Strings.Mid to String.Substring. 您也不会看到Strings.Mid到String.Substring。 Code looking for a "0" to return from Strings.Instr or Strings.Mid because nothing was found will break, as "0" is now the first index in a successful search. 代码寻找从Strings.InstrStrings.Mid返回的“ 0”,因为没有发现任何内容将中断,因为“ 0”现在是成功搜索中的第一个索引。 You actually need the ensuing errors to determine where you need to adjust your code to look for the proper response (ie, -1 on a search with no results). 实际上,您实际上需要随之而来的错误来确定需要调整代码的位置,以寻找正确的响应(即,搜索为-1,没有结果)。

You need to use the C# equivalent functions something like this: 您需要使用C#等效功能,如下所示:

nPos = sHeadingNm.IndexOf('1'); nPos = sHeadingNm.IndexOf('1');

sHeadingNm = sHeadingNm.Substring( 1, nPos - 1); sHeadingNm = sHeadingNm.Substring(1,nPos-1);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM