String representation of an Enum

后端 未结 30 1927
不思量自难忘°
不思量自难忘° 2020-11-22 02:44

I have the following enumeration:

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

T

相关标签:
30条回答
  • 2020-11-22 03:04

    A lot of great answers here but in my case did not solve what I wanted out of an "string enum", which was:

    1. Usable in a switch statement e.g switch(myEnum)
    2. Can be used in function parameters e.g. foo(myEnum type)
    3. Can be referenced e.g. myEnum.FirstElement
    4. I can use strings e.g. foo("FirstElement") == foo(myEnum.FirstElement)

    1,2 & 4 can actually be solved with a C# Typedef of a string (since strings are switchable in c#)

    3 can be solved by static const strings. So if you have the same needs, this is the simplest approach:

    public sealed class Types
    {
    
        private readonly String name;
    
        private Types(String name)
        {
            this.name = name;
    
        }
    
        public override String ToString()
        {
            return name;
        }
    
        public static implicit operator Types(string str)
        {
            return new Types(str);
    
        }
        public static implicit operator string(Types str)
        {
            return str.ToString();
        }
    
    
        #region enum
    
        public const string DataType = "Data";
        public const string ImageType = "Image";
        public const string Folder = "Folder";
        #endregion
    
    }
    

    This allows for example:

        public TypeArgs(Types SelectedType)
        {
            Types SelectedType = SelectedType
        }
    

    and

    public TypeObject CreateType(Types type)
        {
            switch (type)
            {
    
                case Types.ImageType:
                  //
                    break;
    
                case Types.DataType:
                 //
                    break;
    
            }
        }
    

    Where CreateType can be called with a string or a type. However the downside is that any string is automatically a valid enum, this could be modified but then it would require some kind of init function...or possibly make they explicit cast internal?

    Now if an int value was important to you (perhaps for comparison speed), you could use some ideas from Jakub Šturc fantastic answer and do something a bit crazy, this is my stab at it:

        public sealed class Types
    {
        private static readonly Dictionary<string, Types> strInstance = new Dictionary<string, Types>();
        private static readonly Dictionary<int, Types> intInstance = new Dictionary<int, Types>();
    
        private readonly String name;
        private static int layerTypeCount = 0;
        private int value;
        private Types(String name)
        {
            this.name = name;
            value = layerTypeCount++;
            strInstance[name] = this;
            intInstance[value] = this;
        }
    
        public override String ToString()
        {
            return name;
        }
    
    
        public static implicit operator Types(int val)
        {
            Types result;
            if (intInstance.TryGetValue(val, out result))
                return result;
            else
                throw new InvalidCastException();
        }
    
        public static implicit operator Types(string str)
        {
            Types result;
            if (strInstance.TryGetValue(str, out result))
            {
                return result;
            }
            else
            {
                result = new Types(str);
                return result;
            }
    
        }
        public static implicit operator string(Types str)
        {
            return str.ToString();
        }
    
        public static bool operator ==(Types a, Types b)
        {
            return a.value == b.value;
        }
        public static bool operator !=(Types a, Types b)
        {
            return a.value != b.value;
        }
    
        #region enum
    
        public const string DataType = "Data";
        public const string ImageType = "Image";
    
        #endregion
    
    }
    

    but of course "Types bob = 4;" would be meaningless unless you had initialized them first which would sort of defeat the point...

    But in theory TypeA == TypeB would be quicker...

    0 讨论(0)
  • 2020-11-22 03:06

    Just use the ToString() method

    public enum any{Tomato=0,Melon,Watermelon}
    

    To reference the string Tomato, just use

    any.Tomato.ToString();
    
    0 讨论(0)
  • 2020-11-22 03:06

    Update: Visiting this page, 8 years later, after not touching C# for a long while, looks like my answer is no longer the best solution. I really like the converter solution tied with attribute-functions.

    If you are reading this, please make sure you also check out other answers.
    (hint: they are above this one)


    As most of you, I really liked the selected answer by Jakub Šturc, but I also really hate to copy-paste code, and try to do it as little as I can.

    So I decided I wanted an EnumBase class from which most of the functionality is inherited/built-in, leaving me to focus on the content instead of behavior.

    The main problem with this approach is based on the fact that although Enum values are type-safe instances, the interaction is with the Static implementation of the Enum Class type. So with a little help of generics magic, I think I finally got the correct mix. Hope someone finds this as useful as I did.

    I'll start with Jakub's example, but using inheritance and generics:

    public sealed class AuthenticationMethod : EnumBase<AuthenticationMethod, int>
    {
        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)
            : base( Value, Name ) { }
        public new static IEnumerable<AuthenticationMethod> All
        { get { return EnumBase<AuthenticationMethod, int>.All; } }
        public static explicit operator AuthenticationMethod(string str)
        { return Parse(str); }
    }
    

    And here is the base class:

    using System;
    using System.Collections.Generic;
    using System.Linq; // for the .AsEnumerable() method call
    
    // E is the derived type-safe-enum class
    // - this allows all static members to be truly unique to the specific
    //   derived class
    public class EnumBase<E, T> where E: EnumBase<E, T>
    {
        #region Instance code
        public T Value { get; private set; }
        public string Name { get; private set; }
    
        protected EnumBase(T EnumValue, string Name)
        {
            Value = EnumValue;
            this.Name = Name;
            mapping.Add(Name, this);
        }
    
        public override string ToString() { return Name; }
        #endregion
    
        #region Static tools
        static private readonly Dictionary<string, EnumBase<E, T>> mapping;
        static EnumBase() { mapping = new Dictionary<string, EnumBase<E, T>>(); }
        protected static E Parse(string name)
        {
            EnumBase<E, T> result;
            if (mapping.TryGetValue(name, out result))
            {
                return (E)result;
            }
    
            throw new InvalidCastException();
        }
        // This is protected to force the child class to expose it's own static
        // method.
        // By recreating this static method at the derived class, static
        // initialization will be explicit, promising the mapping dictionary
        // will never be empty when this method is called.
        protected static IEnumerable<E> All
        { get { return mapping.Values.AsEnumerable().Cast<E>(); } }
        #endregion
    }
    
    0 讨论(0)
  • 2020-11-22 03:06

    I created a base class for creating string-valued enums in .NET. It is just one C# file that you can copy & paste into your projects, or install via NuGet package named StringEnum. GitHub Repo

    • Intellisense will suggest the enum name if the class is annotated with the xml comment <completitionlist>. (Works in both C# and VB)

    Intellisense demo

    • Usage similar to a regular enum:
    ///<completionlist cref="HexColor"/> 
    class HexColor : StringEnum<HexColor>
    {
        public static readonly HexColor Blue = Create("#FF0000");
        public static readonly HexColor Green = Create("#00FF00");
        public static readonly HexColor Red = Create("#000FF");
    }
    
        // Static Parse Method
        HexColor.Parse("#FF0000") // => HexColor.Red
        HexColor.Parse("#ff0000", caseSensitive: false) // => HexColor.Red
        HexColor.Parse("invalid") // => throws InvalidOperationException
    
        // Static TryParse method.
        HexColor.TryParse("#FF0000") // => HexColor.Red
        HexColor.TryParse("#ff0000", caseSensitive: false) // => HexColor.Red
        HexColor.TryParse("invalid") // => null
    
        // Parse and TryParse returns the preexistent instances
        object.ReferenceEquals(HexColor.Parse("#FF0000"), HexColor.Red) // => true
    
        // Conversion from your `StringEnum` to `string`
        string myString1 = HexColor.Red.ToString(); // => "#FF0000"
        string myString2 = HexColor.Red; // => "#FF0000" (implicit cast)
    

    Instalation:

    • Paste the following StringEnum base class to your project. (latest version)
    • Or install StringEnum NuGet package, which is based on .Net Standard 1.0 so it runs on .Net Core >= 1.0, .Net Framework >= 4.5, Mono >= 4.6, etc.
        /// <summary>
        /// Base class for creating string-valued enums in .NET.<br/>
        /// Provides static Parse() and TryParse() methods and implicit cast to string.
        /// </summary>
        /// <example> 
        /// <code>
        /// class Color : StringEnum &lt;Color&gt;
        /// {
        ///     public static readonly Color Blue = Create("Blue");
        ///     public static readonly Color Red = Create("Red");
        ///     public static readonly Color Green = Create("Green");
        /// }
        /// </code>
        /// </example>
        /// <typeparam name="T">The string-valued enum type. (i.e. class Color : StringEnum&lt;Color&gt;)</typeparam>
        public abstract class StringEnum<T> : IEquatable<T> where T : StringEnum<T>, new()
        {
            protected string Value;
            private static Dictionary<string, T> valueDict = new Dictionary<string, T>();
            protected static T Create(string value)
            {
                if (value == null)
                    return null; // the null-valued instance is null.
    
                var result = new T() { Value = value };
                valueDict.Add(value, result);
                return result;
            }
    
            public static implicit operator string(StringEnum<T> enumValue) => enumValue.Value;
            public override string ToString() => Value;
    
            public static bool operator !=(StringEnum<T> o1, StringEnum<T> o2) => o1?.Value != o2?.Value;
            public static bool operator ==(StringEnum<T> o1, StringEnum<T> o2) => o1?.Value == o2?.Value;
    
            public override bool Equals(object other) => this.Value.Equals((other as T)?.Value ?? (other as string));
            bool IEquatable<T>.Equals(T other) => this.Value.Equals(other.Value);
            public override int GetHashCode() => Value.GetHashCode();
    
            /// <summary>
            /// Parse the <paramref name="value"/> specified and returns a valid <typeparamref name="T"/> or else throws InvalidOperationException.
            /// </summary>
            /// <param name="value">The string value representad by an instance of <typeparamref name="T"/>. Matches by string value, not by the member name.</param>
            /// <param name="caseSensitive">If true, the strings must match case and takes O(log n). False allows different case but is little bit slower (O(n))</param>
            public static T Parse(string value, bool caseSensitive = true)
            {
                var result = TryParse(value, caseSensitive);
                if (result == null)
                    throw new InvalidOperationException((value == null ? "null" : $"'{value}'") + $" is not a valid {typeof(T).Name}");
    
                return result;
            }
    
            /// <summary>
            /// Parse the <paramref name="value"/> specified and returns a valid <typeparamref name="T"/> or else returns null.
            /// </summary>
            /// <param name="value">The string value representad by an instance of <typeparamref name="T"/>. Matches by string value, not by the member name.</param>
            /// <param name="caseSensitive">If true, the strings must match case. False allows different case but is slower: O(n)</param>
            public static T TryParse(string value, bool caseSensitive = true)
            {
                if (value == null) return null;
                if (valueDict.Count == 0) System.Runtime.CompilerServices.RuntimeHelpers.RunClassConstructor(typeof(T).TypeHandle); // force static fields initialization
                if (caseSensitive)
                {
                    if (valueDict.TryGetValue(value, out T item))
                        return item;
                    else
                        return null;
                }
                else
                {
                    // slower O(n) case insensitive search
                    return valueDict.FirstOrDefault(f => f.Key.Equals(value, StringComparison.OrdinalIgnoreCase)).Value;
                    // Why Ordinal? => https://esmithy.net/2007/10/15/why-stringcomparisonordinal-is-usually-the-right-choice/
                }
            }
        }
    
    0 讨论(0)
  • 2020-11-22 03:06

    If I'm understanding you correctly, you can simply use .ToString() to retrieve the name of the enum from the value (Assuming it's already cast as the Enum); If you had the naked int (lets say from a database or something) you can first cast it to the enum. Both methods below will get you the enum name.

    AuthenticationMethod myCurrentSetting = AuthenticationMethod.FORMS;
    Console.WriteLine(myCurrentSetting); // Prints: FORMS
    string name = Enum.GetNames(typeof(AuthenticationMethod))[(int)myCurrentSetting-1];
    Console.WriteLine(name); // Prints: FORMS
    

    Keep in mind though, the second technique assumes you are using ints and your index is 1 based (not 0 based). The function GetNames also is quite heavy by comparison, you are generating a whole array each time it's called. As you can see in the first technique, .ToString() is actually called implicitly. Both of these are already mentioned in the answers of course, I'm just trying to clarify the differences between them.

    0 讨论(0)
  • 2020-11-22 03:07

    For larger string enum sets, the listed examples can become tiresome. If you want a list of status codes, or a list of other string based enums, an attribute system is annoying to use, and a static class with instances of itself is annoying to configure. For my own solution, I make use of T4 templating to make it easier to have string-backed enums. The result comes out similar to how the HttpMethod class works.

    You can use it like this:

        string statusCode = ResponseStatusCode.SUCCESS; // Automatically converts to string when needed
        ResponseStatusCode codeByValueOf = ResponseStatusCode.ValueOf(statusCode); // Returns null if not found
    
        // Implements TypeConverter so you can use it with string conversion methods.
        var converter = System.ComponentModel.TypeDescriptor.GetConverter(typeof(ResponseStatusCode));
        ResponseStatusCode code = (ResponseStatusCode) converter.ConvertFromInvariantString(statusCode);
    
        // You can get a full list of the values
        bool canIterateOverValues = ResponseStatusCode.Values.Any(); 
    
        // Comparisons are by value of the "Name" property. Not by memory pointer location.
        bool implementsByValueEqualsEqualsOperator = "SUCCESS" == ResponseStatusCode.SUCCESS; 
    

    You start out with a Enum.tt file.

    <#@ include file="StringEnum.ttinclude" #>
    
    
    <#+
    public static class Configuration
    {
        public static readonly string Namespace = "YourName.Space";
        public static readonly string EnumName = "ResponseStatusCode";
        public static readonly bool IncludeComments = true;
    
        public static readonly object Nodes = new
        {
            SUCCESS = "The response was successful.",
            NON_SUCCESS = "The request was not successful.",
            RESOURCE_IS_DISCONTINUED = "The resource requested has been discontinued and can no longer be accessed."
        };
    }
    #>
    

    Then, you add in your StringEnum.ttinclude file.

    <#@ template debug="false" hostspecific="false" language="C#" #>
    <#@ assembly name="System.Core" #>
    <#@ import namespace="System" #>
    <#@ import namespace="System.Linq" #>
    <#@ import namespace="System.Text" #>
    <#@ import namespace="System.Reflection" #>
    <#@ import namespace="System.Collections.Generic" #>
    <#@ output extension=".cs" #>
    <#@ CleanupBehavior processor="T4VSHost" CleanupAfterProcessingtemplate="true" #>
    
    //------------------------------------------------------------------------------
    // <auto-generated>
    //     This code was generated by a tool.
    //
    //     Changes to this file may cause incorrect behavior and will be lost if
    //     the code is regenerated.
    // </auto-generated>
    //------------------------------------------------------------------------------
    
    using System;
    using System.Linq;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Globalization;
    
    namespace <#= Configuration.Namespace #>
    {
        /// <summary>
        /// TypeConverter implementations allow you to use features like string.ToNullable(T).
        /// </summary>
        public class <#= Configuration.EnumName #>TypeConverter : TypeConverter
        {
            public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
            {
                return sourceType == typeof(string) || base.CanConvertFrom(context, sourceType);
            }
    
            public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
            {
                var casted = value as string;
    
                if (casted != null)
                {
                    var result = <#= Configuration.EnumName #>.ValueOf(casted);
                    if (result != null)
                    {
                        return result;
                    }
                }
    
                return base.ConvertFrom(context, culture, value);
            }
    
            public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
            {
                var casted = value as <#= Configuration.EnumName #>;
                if (casted != null && destinationType == typeof(string))
                {
                    return casted.ToString();
                }
    
                return base.ConvertTo(context, culture, value, destinationType);
            }
        }
    
        [TypeConverter(typeof(<#= Configuration.EnumName #>TypeConverter))]
        public class <#= Configuration.EnumName #> : IEquatable<<#= Configuration.EnumName #>>
        {
    //---------------------------------------------------------------------------------------------------
    // V A L U E S _ L I S T
    //---------------------------------------------------------------------------------------------------
    <# Write(Helpers.PrintEnumProperties(Configuration.Nodes)); #>
    
            private static List<<#= Configuration.EnumName #>> _list { get; set; } = null;
            public static List<<#= Configuration.EnumName #>> ToList()
            {
                if (_list == null)
                {
                    _list = typeof(<#= Configuration.EnumName #>).GetFields().Where(x => x.IsStatic && x.IsPublic && x.FieldType == typeof(<#= Configuration.EnumName #>))
                        .Select(x => x.GetValue(null)).OfType<<#= Configuration.EnumName #>>().ToList();
                }
    
                return _list;
            }
    
            public static List<<#= Configuration.EnumName #>> Values()
            {
                return ToList();
            }
    
            /// <summary>
            /// Returns the enum value based on the matching Name of the enum. Case-insensitive search.
            /// </summary>
            /// <param name="key"></param>
            /// <returns></returns>
            public static <#= Configuration.EnumName #> ValueOf(string key)
            {
                return ToList().FirstOrDefault(x => string.Compare(x.Name, key, true) == 0);
            }
    
    
    //---------------------------------------------------------------------------------------------------
    // I N S T A N C E _ D E F I N I T I O N
    //---------------------------------------------------------------------------------------------------      
            public string Name { get; private set; }
            public string Description { get; private set; }
            public override string ToString() { return this.Name; }
    
            /// <summary>
            /// Implcitly converts to string.
            /// </summary>
            /// <param name="d"></param>
            public static implicit operator string(<#= Configuration.EnumName #> d)
            {
                return d.ToString();
            }
    
            /// <summary>
            /// Compares based on the == method. Handles nulls gracefully.
            /// </summary>
            /// <param name="a"></param>
            /// <param name="b"></param>
            /// <returns></returns>
            public static bool operator !=(<#= Configuration.EnumName #> a, <#= Configuration.EnumName #> b)
            {
                return !(a == b);
            }
    
            /// <summary>
            /// Compares based on the .Equals method. Handles nulls gracefully.
            /// </summary>
            /// <param name="a"></param>
            /// <param name="b"></param>
            /// <returns></returns>
            public static bool operator ==(<#= Configuration.EnumName #> a, <#= Configuration.EnumName #> b)
            {
                return a?.ToString() == b?.ToString();
            }
    
            /// <summary>
            /// Compares based on the .ToString() method
            /// </summary>
            /// <param name="o"></param>
            /// <returns></returns>
            public override bool Equals(object o)
            {
                return this.ToString() == o?.ToString();
            }
    
            /// <summary>
            /// Compares based on the .ToString() method
            /// </summary>
            /// <param name="other"></param>
            /// <returns></returns>
            public bool Equals(<#= Configuration.EnumName #> other)
            {
                return this.ToString() == other?.ToString();
            }
    
            /// <summary>
            /// Compares based on the .Name property
            /// </summary>
            /// <returns></returns>
            public override int GetHashCode()
            {
                return this.Name.GetHashCode();
            }
        }
    }
    
    <#+
    
    public static class Helpers
    {
            public static string PrintEnumProperties(object nodes)
            {
                string o = "";
                Type nodesTp = Configuration.Nodes.GetType();
                PropertyInfo[] props = nodesTp.GetProperties().OrderBy(p => p.Name).ToArray();
    
                for(int i = 0; i < props.Length; i++)
                {
                    var prop = props[i];
                    if (Configuration.IncludeComments)
                    {
                        o += "\r\n\r\n";
                        o += "\r\n        ///<summary>";
                        o += "\r\n        /// "+Helpers.PrintPropertyValue(prop, Configuration.Nodes);
                        o += "\r\n        ///</summary>";
                    }
    
                    o += "\r\n        public static readonly "+Configuration.EnumName+" "+prop.Name+ " = new "+Configuration.EnumName+"(){ Name = \""+prop.Name+"\", Description = "+Helpers.PrintPropertyValue(prop, Configuration.Nodes)+ "};";
                }
    
                o += "\r\n\r\n";
    
                return o;
            }
    
            private static Dictionary<string, string> GetValuesMap()
            {
                Type nodesTp = Configuration.Nodes.GetType();
                PropertyInfo[] props= nodesTp.GetProperties();
                var dic = new Dictionary<string,string>();
                for(int i = 0; i < props.Length; i++)
                {
                    var prop = nodesTp.GetProperties()[i];
                    dic[prop.Name] = prop.GetValue(Configuration.Nodes).ToString();
                }
                return dic;
            }
    
            public static string PrintMasterValuesMap(object nodes)
            {
                Type nodesTp = Configuration.Nodes.GetType();
                PropertyInfo[] props= nodesTp.GetProperties();
                string o = "        private static readonly Dictionary<string, string> ValuesMap = new Dictionary<string, string>()\r\n        {";
                for(int i = 0; i < props.Length; i++)
                {
                    var prop = nodesTp.GetProperties()[i];
                    o += "\r\n            { \""+prop.Name+"\", "+(Helpers.PrintPropertyValue(prop,Configuration.Nodes)+" },");
                }
                o += ("\r\n        };\r\n");
    
                return o;
            }
    
    
            public static string PrintPropertyValue(PropertyInfo prop, object objInstance)
            {
                switch(prop.PropertyType.ToString()){
                    case "System.Double":
                        return prop.GetValue(objInstance).ToString()+"D";
                    case "System.Float":
                        return prop.GetValue(objInstance).ToString()+"F";
                    case "System.Decimal":
                        return prop.GetValue(objInstance).ToString()+"M";
                    case "System.Long":
                        return prop.GetValue(objInstance).ToString()+"L";
                    case "System.Boolean":
                    case "System.Int16":
                    case "System.Int32":
                        return prop.GetValue(objInstance).ToString().ToLowerInvariant();
                    case "System.String":
                        return "\""+prop.GetValue(objInstance)+"\"";
                }
    
                return prop.GetValue(objInstance).ToString();
            }
    
            public static string _ (int numSpaces)
            {
                string o = "";
                for(int i = 0; i < numSpaces; i++){
                    o += " ";
                }
    
                return o;
            }
    }
    #>
    

    Finally, you recompile your Enum.tt file and the output looks like this:

    //------------------------------------------------------------------------------
    // <auto-generated>
    //     This code was generated by a tool.
    //
    //     Changes to this file may cause incorrect behavior and will be lost if
    //     the code is regenerated.
    // </auto-generated>
    //------------------------------------------------------------------------------
    
    using System;
    using System.Linq;
    using System.Collections.Generic;
    
    namespace YourName.Space
    {
        public class ResponseStatusCode
        {
    //---------------------------------------------------------------------------------------------------
    // V A L U E S _ L I S T 
    //---------------------------------------------------------------------------------------------------
    
    
    
            ///<summary>
            /// "The response was successful."
            ///</summary>
            public static readonly ResponseStatusCode SUCCESS = new ResponseStatusCode(){ Name = "SUCCESS", Description = "The response was successful."};
    
    
            ///<summary>
            /// "The request was not successful."
            ///</summary>
            public static readonly ResponseStatusCode NON_SUCCESS = new ResponseStatusCode(){ Name = "NON_SUCCESS", Description = "The request was not successful."};
    
    
            ///<summary>
            /// "The resource requested has been discontinued and can no longer be accessed."
            ///</summary>
            public static readonly ResponseStatusCode RESOURCE_IS_DISCONTINUED = new ResponseStatusCode(){ Name = "RESOURCE_IS_DISCONTINUED", Description = "The resource requested has been discontinued and can no longer be accessed."};
    
    
            private static List<ResponseStatusCode> _list { get; set; } = null;
            public static List<ResponseStatusCode> ToList()
            {
                if (_list == null)
                {
                    _list = typeof(ResponseStatusCode).GetFields().Where(x => x.IsStatic && x.IsPublic && x.FieldType == typeof(ResponseStatusCode))
                        .Select(x => x.GetValue(null)).OfType<ResponseStatusCode>().ToList();
                }
    
                return _list;
            }
    
            public static List<ResponseStatusCode> Values()
            {
                return ToList();
            }
    
            /// <summary>
            /// Returns the enum value based on the matching Name of the enum. Case-insensitive search.
            /// </summary>
            /// <param name="key"></param>
            /// <returns></returns>
            public static ResponseStatusCode ValueOf(string key)
            {
                return ToList().FirstOrDefault(x => string.Compare(x.Name, key, true) == 0);
            }
    
    
    //---------------------------------------------------------------------------------------------------
    // I N S T A N C E _ D E F I N I T I O N 
    //---------------------------------------------------------------------------------------------------       
            public string Name { get; set; }
            public string Description { get; set; }
            public override string ToString() { return this.Name; }
    
            /// <summary>
            /// Implcitly converts to string.
            /// </summary>
            /// <param name="d"></param>
            public static implicit operator string(ResponseStatusCode d)
            {
                return d.ToString();
            }
    
            /// <summary>
            /// Compares based on the == method. Handles nulls gracefully.
            /// </summary>
            /// <param name="a"></param>
            /// <param name="b"></param>
            /// <returns></returns>
            public static bool operator !=(ResponseStatusCode a, ResponseStatusCode b)
            {
                return !(a == b);
            }
    
            /// <summary>
            /// Compares based on the .Equals method. Handles nulls gracefully.
            /// </summary>
            /// <param name="a"></param>
            /// <param name="b"></param>
            /// <returns></returns>
            public static bool operator ==(ResponseStatusCode a, ResponseStatusCode b)
            {
                return a?.ToString() == b?.ToString();
            }
    
            /// <summary>
            /// Compares based on the .ToString() method
            /// </summary>
            /// <param name="o"></param>
            /// <returns></returns>
            public override bool Equals(object o)
            {
                return this.ToString() == o?.ToString();
            }
    
            /// <summary>
            /// Compares based on the .Name property
            /// </summary>
            /// <returns></returns>
            public override int GetHashCode()
            {
                return this.Name.GetHashCode();
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题