While C# enums inherently map to integer values, effectively associating them with descriptive strings enhances readability and maintainability. This article explores techniques beyond the basic enum definition to achieve this.
A robust method involves using static properties within a class. This approach provides a similar user experience to enums but allows for direct string representation. Here's an example using a LogCategory
class:
<code class="language-csharp">public class LogCategory { private LogCategory(string value) { Value = value; } public string Value { get; private set; } public static LogCategory Trace { get { return new LogCategory("Trace"); } } public static LogCategory Debug { get { return new LogCategory("Debug"); } } public static LogCategory Info { get { return new LogCategory("Info"); } } public static LogCategory Warning { get { return new LogCategory("Warning"); } } public static LogCategory Error { get { return new LogCategory("Error"); } } public override string ToString() { return Value; } }</code>
This class mirrors enum functionality. The Value
property holds the string representation, accessible via static properties like LogCategory.Info
.
Usage example:
<code class="language-csharp">public static void WriteLog(string message, LogCategory category) { var logEntry = new LogEntry { Message = message }; Logger.Write(logEntry, category.Value); } // Example call WriteLog("This is a log message.", LogCategory.Warning);</code>
This approach retains the clarity and ease of use of enums while providing the necessary string mappings for improved code clarity.
The above is the detailed content of How Can I Map C# Enumerations to Strings Effectively?. For more information, please follow other related articles on the PHP Chinese website!