Maison >développement back-end >C++ >Comment obtenir une représentation de chaîne des valeurs d'énumération en C #?

Comment obtenir une représentation de chaîne des valeurs d'énumération en C #?

Mary-Kate Olsen
Mary-Kate Olsenoriginal
2025-01-29 08:23:10579parcourir

How to Get String Representation of Enum Values in C#?

Représentation de chaîne d'un enum

Considérez l'énumération suivante:

public enum AuthenticationMethod
{
    FORMS = 1,
    WINDOWSAUTHENTICATION = 2,
    SINGLESIGNON = 3
}

Cependant, vous avez besoin de la chaîne "formulaires" lors de la demande d'authentification. Formulaires, pas l'ID de 1.

L'attribut personnalisé "StringValue" peut résoudre ce problème:

public class StringValue : System.Attribute
{
    private readonly string _value;

    public StringValue(string value)
    {
        _value = value;
    }

    public string Value
    {
        get { return _value; }
    }

}

Ensuite, vous pouvez appliquer cet attribut à votre énumération:

public enum AuthenticationMethod
{
    [StringValue("FORMS")]
    FORMS = 1,
    [StringValue("WINDOWS")]
    WINDOWSAUTHENTICATION = 2,
    [StringValue("SSO")]
    SINGLESIGNON = 3
}

Pour récupérer ce stringValue, vous aurez besoin de ce qui suit:

public static class StringEnum
{
    public static string GetStringValue(Enum value)
    {
        string output = null;
        Type type = value.GetType();

        // Look for our 'StringValueAttribute' in the field's custom attributes
        FieldInfo fi = type.GetField(value.ToString());
        StringValue[] attrs = fi.GetCustomAttributes(typeof(StringValue), false) as StringValue[];
        if (attrs.Length > 0)
        {
            output = attrs[0].Value;
        }

        return output;
    }
}

Cette solution vous permet d'obtenir la valeur de chaîne pour les énumérations comme celle-ci:

string valueOfAuthenticationMethod = StringEnum.GetStringValue(AuthenticationMethod.FORMS);

cependant, cependant, Une meilleure solution est le modèle de type-safe-enum:

public sealed class AuthenticationMethod {

    private readonly String name;
    private readonly int value;

    public static readonly AuthenticationMethod FORMS = new AuthenticationMethod (1, "FORMS");
    public static readonly AuthenticationMethod WINDOWSAUTHENTICATION = new AuthenticationMethod (2, "WINDOWS");
    public static readonly AuthenticationMethod SINGLESIGNON = new AuthenticationMethod (3, "SSN");        

    private AuthenticationMethod(int value, String name){
        this.name = name;
        this.value = value;
    }

    public override String ToString(){
        return name;
    }

}

pour la conversion de type explicite (ou implicite), ajoutez un champ statique avec mappage, remplissez le mappage dans le constructeur d'instance et ajoutez un utilisateur- Opérateur de conversion de type défini:

& lt; pré & gt; dictionnaire de lecture statique privé & lt; String, AuthenticationMethod & gt; instance = new Dictionary & lt; String, AuthenticationMethod & gt; ();
instance [name] = this;
public static explicit operator authenticationMethod (String str)
{

AuthenticationMethod result;
if (instance.TryGetValue(str, out result))
    return result;
else
    throw new InvalidCastException();

} & lt; / pre & gt;

Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!

Déclaration:
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn