简体   繁体   中英

Tried to convert VB code to C# but error occurred

I did convert the VB code to below C# code, but error occurred. I am getting error in Strings.InStr and Strings.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:

Strings.InStr has equivalent of String.IndexOf

Strings.Mid has equivalent of String.Substring

Your problem must be that Strings.InStr and Strings.Mid are not standard methods in C#, but in VB.net. You should add probably using Microsoft.VisualBasic in order to use them, although i'd recommend to use C# equivalent methods.

Better stated, you let the Telerik converter convert the code. 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.

For this reason, you don't get an automatic conversion of Strings.InStr to String.IndexOf . You also won't see Strings.Mid to 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. 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).

You need to use the C# equivalent functions something like this:

nPos = sHeadingNm.IndexOf('1');

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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