web-dev-qa-db-fra.com

Quel est l'équivalent des fonctions Asc () et Chr () de VB en C #?

VB a quelques fonctions natives pour convertir un caractère en une valeur ASCII et vice versa - Asc () et Chr ().

Maintenant, je dois obtenir la fonctionnalité équivalente en C #. Quel est le meilleur moyen?

27
Shaul Behr

Vous pouvez toujours ajouter une référence à Microsoft.VisualBasic et utiliser ensuite les mêmes méthodes: Strings.Chr et Strings.Asc .

C'est le moyen le plus simple d'obtenir exactement la même fonctionnalité.

28
Garry Shutler

Pour Asc(), vous pouvez transtyper la char en une int comme ceci:

int i = (int)your_char;

et pour Chr(), vous pouvez renvoyer une char à partir d'une int comme ceci:

char c = (char)your_int;

Voici un petit programme qui montre la chose entière:

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);
    }
}
20
Andrew Hare

Je les ai obtenus avec resharper, le code exact est exécuté par VB sur votre machine 

/// <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]);
}

Les ressources ne sont que des messages d'erreur stockés. Par conséquent, la façon dont vous voulez les ignorer et les deux autres méthodes auxquelles vous n'avez pas accès sont les suivantes:

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

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

Strings.Asc n'est pas équivalent à une conversion C # en clair pour des caractères non ASCII pouvant aller au-delà de 127 valeurs de code. La réponse trouvée sur 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 revient à quelque chose comme ceci:

    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;
    }

Ou, si vous voulez que le contrat de lecture ajoute une référence à Microsoft.VisualBasic Assembly.

1
dmihailescu

Pour Chr (), vous pouvez utiliser:

char chr = (char)you_char_value;
1
Tony

Ajouter cette méthode en 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;
            }
        }

`

0
user10960826

en C #, vous pouvez utiliser l'instruction Char.ConvertFromUtf32

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

l'équivalent de VB 

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

Aucune référence Microsoft.VisualBasic requise

0
Georg