prosource

C#에서 VB의 As() 및 Chr() 함수에 해당하는 것은 무엇입니까?

probook 2023. 5. 28. 20:54
반응형

C#에서 VB의 As() 및 Chr() 함수에 해당하는 것은 무엇입니까?

VB에는 문자를 ASCII 값으로 변환하거나 ASCII 값으로 변환하는 몇 가지 기본 기능(Asc() 및 Chr()이 있습니다.

이제 저는 C#에서 동등한 기능을 얻어야 합니다.가장 좋은 방법은 무엇입니까?

Microsoft에 대한 참조를 언제든지 추가할 수 있습니다.Visual Basic과 동일한 방법을 사용합니다.현악기.크리스와 스트링스.아스.

이것이 바로 동일한 기능을 얻는 가장 쉬운 방법입니다.

위해서Asc()캐스팅할 수 있습니다.char완전히int다음과 같이:

int i = (int)your_char;

에 대해서도Chr()당신은 다시 a로 던질 수 있습니다.char에서int다음과 같이:

char c = (char)your_int;

여기 전체를 보여주는 작은 프로그램이 있습니다.

using System;

class Program
{
    static void Main()
    {
        char c = 'A';
        int i = 65;

        // both print "True"
        Console.WriteLine(i == (int)c);
        Console.WriteLine(c == (char)i);
    }
}

저는 이것들을 리샤퍼를 사용하여 구했습니다. 정확한 코드는 당신의 기계에서 VB에 의해 실행됩니다.

/// <summary>
/// Returns the character associated with the specified character code.
/// </summary>
/// 
/// <returns>
/// Returns the character associated with the specified character code.
/// </returns>
/// <param name="CharCode">Required. An Integer expression representing the <paramref name="code point"/>, or character code, for the character.</param><exception cref="T:System.ArgumentException"><paramref name="CharCode"/> &lt; 0 or &gt; 255 for Chr.</exception><filterpriority>1</filterpriority>
public static char Chr(int CharCode)
{
  if (CharCode < (int) short.MinValue || CharCode > (int) ushort.MaxValue)
    throw new ArgumentException(Utils.GetResourceString("Argument_RangeTwoBytes1", new string[1]
    {
      "CharCode"
    }));
  if (CharCode >= 0 && CharCode <= (int) sbyte.MaxValue)
    return Convert.ToChar(CharCode);
  try
  {
    Encoding encoding = Encoding.GetEncoding(Utils.GetLocaleCodePage());
    if (encoding.IsSingleByte && (CharCode < 0 || CharCode > (int) byte.MaxValue))
      throw ExceptionUtils.VbMakeException(5);
    char[] chars = new char[2];
    byte[] bytes = new byte[2];
    Decoder decoder = encoding.GetDecoder();
    if (CharCode >= 0 && CharCode <= (int) byte.MaxValue)
    {
      bytes[0] = checked ((byte) (CharCode & (int) byte.MaxValue));
      decoder.GetChars(bytes, 0, 1, chars, 0);
    }
    else
    {
      bytes[0] = checked ((byte) ((CharCode & 65280) >> 8));
      bytes[1] = checked ((byte) (CharCode & (int) byte.MaxValue));
      decoder.GetChars(bytes, 0, 2, chars, 0);
    }
    return chars[0];
  }
  catch (Exception ex)
  {
    throw ex;
  }
}


/// <summary>
/// Returns an Integer value representing the character code corresponding to a character.
/// </summary>
/// 
/// <returns>
/// Returns an Integer value representing the character code corresponding to a character.
/// </returns>
/// <param name="String">Required. Any valid Char or String expression. If <paramref name="String"/> is a String expression, only the first character of the string is used for input. If <paramref name="String"/> is Nothing or contains no characters, an <see cref="T:System.ArgumentException"/> error occurs.</param><filterpriority>1</filterpriority>
public static int Asc(char String)
{
  int num1 = Convert.ToInt32(String);
  if (num1 < 128)
    return num1;
  try
  {
    Encoding fileIoEncoding = Utils.GetFileIOEncoding();
    char[] chars = new char[1]
    {
      String
    };
    if (fileIoEncoding.IsSingleByte)
    {
      byte[] bytes = new byte[1];
      fileIoEncoding.GetBytes(chars, 0, 1, bytes, 0);
      return (int) bytes[0];
    }
    byte[] bytes1 = new byte[2];
    if (fileIoEncoding.GetBytes(chars, 0, 1, bytes1, 0) == 1)
      return (int) bytes1[0];
    if (BitConverter.IsLittleEndian)
    {
      byte num2 = bytes1[0];
      bytes1[0] = bytes1[1];
      bytes1[1] = num2;
    }
    return (int) BitConverter.ToInt16(bytes1, 0);
  }
  catch (Exception ex)
  {
    throw ex;
  }
}


/// <summary>
/// Returns an Integer value representing the character code corresponding to a character.
/// </summary>
/// 
/// <returns>
/// Returns an Integer value representing the character code corresponding to a character.
/// </returns>
/// <param name="String">Required. Any valid Char or String expression. If <paramref name="String"/> is a String expression, only the first character of the string is used for input. If <paramref name="String"/> is Nothing or contains no characters, an <see cref="T:System.ArgumentException"/> error occurs.</param><filterpriority>1</filterpriority>
public static int Asc(string String)
{
  if (String == null || String.Length == 0)
    throw new ArgumentException(Utils.GetResourceString("Argument_LengthGTZero1", new string[1]
    {
      "String"
    }));
  return Strings.Asc(String[0]);
}

리소스는 저장된 오류 메시지일 뿐이므로 리소스를 무시하고 액세스할 수 없는 다른 두 가지 방법은 다음과 같습니다.

internal static Encoding GetFileIOEncoding()
{
    return Encoding.Default;
}

internal static int GetLocaleCodePage()
{
    return Thread.CurrentThread.CurrentCulture.TextInfo.ANSICodePage;
}

줄들.As는 127 코드 값을 초과할 수 있는 ASCII가 아닌 문자의 일반 C# 캐스트와 같지 않습니다.제가 https://social.msdn.microsoft.com/Forums/vstudio/en-US/13fec271-9a97-4b71-ab28-4911ff3ecca0/equivalent-in-c-of-asc-chr-functions-of-vb?forum=csharpgeneral 에서 찾은 답은 다음과 같습니다.

    static int Asc(char c)
    {
        int converted = c;
        if (converted >= 0x80)
        {
            byte[] buffer = new byte[2];
            // if the resulting conversion is 1 byte in length, just use the value
            if (System.Text.Encoding.Default.GetBytes(new char[] { c }, 0, 1, buffer, 0) == 1)
            {
                converted = buffer[0];
            }
            else
            {
                // byte swap bytes 1 and 2;
                converted = buffer[0] << 16 | buffer[1];
            }
        }
        return converted;
    }

또는 읽기 거래를 원하는 경우 Microsoft에 대한 참조를 추가합니다.Visual Basic 어셈블리입니다.

Chr()의 경우 다음을 사용할 수 있습니다.

char chr = (char)you_char_value;

C#에서는 Char를 사용할 수 있습니다.ConvertFromUtf32 문

int intValue = 65;                                \\ Letter A    
string strVal = Char.ConvertFromUtf32(intValue);

VB의 등가물

Dim intValue as integer = 65     
Dim strValue As String = Char.ConvertFromUtf32(intValue) 

Microsoft 없음.VisualBasic 참조가 필요

이 메서드를 C# '에 추가합니다.

private  int Asc(char String)
        {
            int int32 = Convert.ToInt32(String);
            if (int32 < 128)
                return int32;
            try
            {
                Encoding fileIoEncoding = Encoding.Default;
                char[] chars = new char[1] { String };
                if (fileIoEncoding.IsSingleByte)
                {
                    byte[] bytes = new byte[1];
                    fileIoEncoding.GetBytes(chars, 0, 1, bytes, 0);
                    return (int)bytes[0];
                }
                byte[] bytes1 = new byte[2];
                if (fileIoEncoding.GetBytes(chars, 0, 1, bytes1, 0) == 1)
                    return (int)bytes1[0];
                if (BitConverter.IsLittleEndian)
                {
                    byte num = bytes1[0];
                    bytes1[0] = bytes1[1];
                    bytes1[1] = num;
                }
                return (int)BitConverter.ToInt16(bytes1, 0);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

`

Microsoft에서 As() 함수를 추출했습니다.VisualBasic.dll:

    public static int Asc(char String)
    {
        int num;
        byte[] numArray;
        int num1 = Convert.ToInt32(String);
        if (num1 >= 128)
        {
            try
            {
                Encoding fileIOEncoding = Encoding.Default;
                char[] str = new char[] { String };
                if (!fileIOEncoding.IsSingleByte)
                {
                    numArray = new byte[2];
                    if (fileIOEncoding.GetBytes(str, 0, 1, numArray, 0) != 1)
                    {
                        if (BitConverter.IsLittleEndian)
                        {
                            byte num2 = numArray[0];
                            numArray[0] = numArray[1];
                            numArray[1] = num2;
                        }
                        num = BitConverter.ToInt16(numArray, 0);
                    }
                    else
                    {
                        num = numArray[0];
                    }
                }
                else
                {
                    numArray = new byte[1];
                    fileIOEncoding.GetBytes(str, 0, 1, numArray, 0);
                    num = numArray[0];
                }
            }
            catch (Exception exception)
            {
                throw exception;
            }
        }
        else
        {
            num = num1;
        }
        return num;
    }

//함수를 만들 수 있으므로 프로그램을 변경할 필요가 없습니다.

 private int Chr(int i)
  {
    return (char)i;
  }

소너 괴눌 덕분에

다음 루틴은 코드 페이지가 1252인 .net 표준 2.0 + .net 5 및 Classic ASP/VB6 클라이언트의 COM Interop 서버 환경에서 작동합니다.

다른 코드 페이지와 함께 테스트하지 않았습니다.

   public static int Asc(char String)
    {
        int int32 = Convert.ToInt32(String);
        if (int32 < 128)
            return int32;
        Encoding encoding = CodePagesEncodingProvider.Instance.GetEncoding(Thread.CurrentThread.CurrentCulture.TextInfo.ANSICodePage);
        char[] chars = new char[1] { String };
        if (encoding.IsSingleByte)
        {
            byte[] bytes = new byte[1];
            encoding.GetBytes(chars, 0, 1, bytes, 0);
            return (int)bytes[0];
        }
        byte[] bytes1 = new byte[2];
        if (encoding.GetBytes(chars, 0, 1, bytes1, 0) == 1)
            return (int)bytes1[0];
        if (BitConverter.IsLittleEndian)
        {
            byte num = bytes1[0];
            bytes1[0] = bytes1[1];
            bytes1[1] = num;
        }
        return (int)BitConverter.ToInt16(bytes1, 0);
    }
 //Char to Int - ASC("]")
 int lIntAsc = (int)Char.Parse("]");
 Console.WriteLine(lIntAsc); //Return 91



 //Int to Char

char lChrChar = (char)91;
Console.WriteLine(lChrChar ); //Return "]"

주어진 char, inti, 함수 fi(int) 및 fc(char):

char에서 int(VB As())로: char를 int로 명시적으로 캐스팅합니다.int i = (int)c;

또는 암시적으로 캐스팅(수정): fi(char c) {i+= c;}

int에서 char(VB Chr()의 아날로그)로:

인트를 문자로 명시적으로 캐스팅:char c = (char)i, fc(int i) {(char)i};

int가 문자보다 더 넓기 때문에(값 범위가 더 넓기 때문에) 암시적 캐스트는 허용되지 않습니다.

언급URL : https://stackoverflow.com/questions/721201/whats-the-equivalent-of-vbs-asc-and-chr-functions-in-c

반응형