首頁 >後端開發 >C++ >如何在C#中獲取枚舉值的字符串表示形式?

如何在C#中獲取枚舉值的字符串表示形式?

Mary-Kate Olsen
Mary-Kate Olsen原創
2025-01-29 08:23:10511瀏覽

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

>

字符串表示的字符串表示,請考慮以下枚舉:

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

,但是,請求AutheThicationMethod時,您需要字符串“表單”。表單,而不是1的ID。 >

要檢索此字符串value,您將需要以下內容:

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

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

    public string Value
    {
        get { return _value; }
    }

}

>此解決方案允許您獲取這樣的枚舉的字符串值:

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

,但是,一個更好的解決方案是類型安全性- 元素模式:

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

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

用於顯式(或隱式)類型轉換,添加帶有映射的靜態字段,填充映射在實例構造函數中,然後添加一個用戶- 定義的類型轉換運算符:

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

}
< pre> private static patic readonly dictionary< string ,authenticationMethod>實例= new dictionary< string,authenticationMethod>();

instance [name] = this;

> public static expatic equipit Operator authenticationMethod(String str)

以上是如何在C#中獲取枚舉值的字符串表示形式?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn