各位前輩好
小弟對自己的一段程式碼很不滿意,但又想不出更好的寫法
希望前輩能不吝教導,謝謝!
public enum Status
{
A = 0,
B = -1,
C = 2
// ...
}
public static string STR_A = "AAA";
public static string STR_B = "BBB";
public static string STR_C = "CCC";
// ...
public string Print(Status status)
{
string str = null;
switch(status)
{
case A:
str = STR_A;
break;
case B:
str = STR_B;
break;
case C:
str = STR_C;
break;
// ...
}
return str;
}
主要是想傳入status給Print(),然後得到各個Status對應的字串
但依照目前的寫法,日後如果要增加一個Status都要修改很多地方
維護上會很頭大
提供兩個解法給你參考
解法一:
public enum Status
{
A = 0,
B = -1,
C = 2
}
/// <summary>
/// 變化都供應在這個字典中S
/// </summary>
/// <returns></returns>
public static Dictionary<Status, string> GetMapperDict()
{
Dictionary<Status, string> dict = new Dictionary<Status, string>();
dict[Status.A] = "AAA";
dict[Status.B] = "BBB";
dict[Status.C] = "CCC";
return dict;
}
public static string Print(Status status)
{
string str = string.Empty;
var dict = GetMapperDict();
str = dict[status];
return str;
}
解法二:
public class GetInputAttribute : Attribute
{
public string Content { get; set; }
}
/// <summary>
/// 變化由Enum提供
/// </summary>
public enum Status
{
[GetInput(Content = "AAA")]
A = 0,
[GetInput(Content = "BBB")]
B = -1,
[GetInput(Content = "CCC")]
C = 2
}
/// <summary>
/// 使用反射動態取得資料
/// </summary>
/// <param name="status"></param>
/// <returns></returns>
public static string Print2(Status status)
{
var field = typeof(Status).GetField(status.ToString());
var attr = Attribute.GetCustomAttribute(field, typeof(GetInputAttribute)) as GetInputAttribute;
string str = attr.Content;
return str;
}
拋磚引玉看看...
using System;
public class Program
{
enum Status {AAA, BBB, CCC};
public static void Main()
{
Status myStatus = Status.BBB;
Console.WriteLine("The string for index {0} is {1}", myStatus.ToString("d"), myStatus.ToString("G") );
}
}
我有个不错的解决方案,而且是开源的方案。大致使用代码如下所示:
using System;
using System.ComponentModel;
/*
* The Zongsoft open source project(s) URL is:
* https://github.com/Zongsoft/Zongsoft.CoreLibrary
*/
using Zongsoft.Common;
using Zongsoft.ComponentModel;
public enum Status
{
[Alias("AAA")]
[Description("The is a description about the AAA.")]
A,
[Alias("Baby")]
[Description("...")]
B,
[Alias("*")]
[Description("...")]
Asterisk,
}
internal class Program
{
public static void Main()
{
Status status;
Print(EnumUtility.GetEnumEntry(Status.A));
if(Zongsoft.Common.Convert.TryConvertValue<Status>(2, out status))
Print(EnumUtility.GetEnumEntry(status);
if(Zongsoft.Common.Convert.TryConvertValue<Status>("*", out status))
Print(EnumUtility.GetEnumEntry(status);
if(Zongsoft.Common.Convert.TryConvertValue<Status>("Asterisk", out status))
Print(EnumUtility.GetEnumEntry(status);
foreach(var entry in EnumUtility.GetEnumEntries(typeof(Status), true))
{
Print(entry);
}
}
private static void Print(EnumEntry entry)
{
Console.WriteLine(entry.Name);
Console.WriteLine(entry.Alias);
Console.WriteLine(entry.Description);
Console.WriteLine(entry.Value);
}
}