iT邦幫忙

0

C# 程式碼優化

c#

各位前輩好
小弟對自己的一段程式碼很不滿意,但又想不出更好的寫法
希望前輩能不吝教導,謝謝!

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都要修改很多地方
維護上會很頭大 /images/emoticon/emoticon06.gif

fillano iT邦超人 1 級 ‧ 2017-10-25 15:55:24 檢舉
用Dictionary做做看吧,這樣狀態跟字串都可以放在同一個地方。
把數值與文字做2維陣列
然後用 FOR LOOP 去搜尋就好
陣列可以動態擴充的不是嘛
椅恩啾 iT邦新手 5 級 ‧ 2017-10-25 17:10:03 檢舉
感謝 fillano 和 窮嘶發發發 大大

之前沒用過dictionary,簡單google一下
兩位大大的意思是不是建立一個mapping table
print()就可以從mapping table中去取得字串
這樣看起來確實省了一步,非常謝謝!
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中
1
石頭
iT邦高手 1 級 ‧ 2017-10-25 16:53:33
最佳解答

提供兩個解法給你參考

解法一:


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;
}
看更多先前的回應...收起先前的回應...
椅恩啾 iT邦新手 5 級 ‧ 2017-10-25 17:26:21 檢舉

感謝 dog830228 大大
兩個解法都省了很多步,非常謝謝!

對於第二個解法,覺得很新奇!
[GetInput(Content = "AAA")]
A = 0,
不知道能不能提供這種寫法的關鍵字
讓小弟可以去翻翻文件學習一下

石頭 iT邦高手 1 級 ‧ 2017-10-25 17:37:03 檢舉

第二個解法是使用反射動態獲取標籤上的值

關鍵字在 GetCustomAttribute

可參考

椅恩啾 iT邦新手 5 級 ‧ 2017-10-25 17:46:14 檢舉

感謝 dog830228 大大

上了一課! /images/emoticon/emoticon13.gif

趕緊作筆記

石頭 iT邦高手 1 級 ‧ 2017-10-25 17:50:13 檢舉

大家互相交流 您客氣了

1
海綿寶寶
iT邦大神 1 級 ‧ 2017-10-25 15:33:35

拋磚引玉看看...

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") );
	}
}
看更多先前的回應...收起先前的回應...
尼克 iT邦大師 1 級 ‧ 2017-10-25 15:37:24 檢舉

海綿大!/images/emoticon/emoticon12.gif

如果只是一個單字就可以
如果是段句子,就掛了
/images/emoticon/emoticon05.gif

weiclin iT邦高手 4 級 ‧ 2017-10-25 16:45:56 檢舉

拋"金"引玉

椅恩啾 iT邦新手 5 級 ‧ 2017-10-25 17:19:05 檢舉

感謝 海綿寶寶 大大
但我的狀況會需要一段句子,非常謝謝!

0
钟少
iT邦新手 5 級 ‧ 2019-04-21 20:53:29

我有个不错的解决方案,而且是开源的方案。大致使用代码如下所示:

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

我要發表回答

立即登入回答