c# 呼叫服務返回結果模板化
一般我們返回一個結果,主要有返回值,執行結果資訊,所以定義一個類
public class QuestResult {
/// <summary> /// 返回值 /// </summary> public object Result { get; set; }
/// <summary> /// 結果編碼 /// </summary> public ErrorCode Error { get; set; }
/// <summary> /// 結果編碼描述 /// </summary> public string ErrorMsg { get; set; }
/// <summary> /// 結果附近資訊 /// 主要是異常資訊或者其它描述 /// 例如:結果被擷取 /// </summary> public string ReslutMsg { get; set; }
}
對於返回的結果編碼,採用列舉型方便擴充套件,而且可以為每個結對應的固定一個描述資訊
public enum ErrorCode {
/// <summary> /// 成功 /// </summary> /// [Description("執行成功")] Sucess,
/// <summary> ///執行超時 /// </summary> /// [Description("執行超時")] TimeOut,
/// <summary> /// 執行異常 /// </summary> /// [Description("執行異常")] Exception,
/// <summary> /// 結果被擷取 /// </summary> /// [Description("結果被擷取")] Truncate,
}
再啟用一個擴充套件方法,獲取列舉的描述資訊
/// </summary> public static class CommonExtend { /// <summary> /// 列舉描述 /// </summary> private static Dictionary<string, string> dicEnum = new Dictionary<string, string>(); /// <summary> /// 列舉描述特性獲取資訊 /// </summary> /// <param name="value">列舉</param> /// <param name="isNameInstend">沒有特性時是否直接使用欄位名稱</param> /// <returns></returns> public static string EnumDescription(this Enum value,bool isNameInstend=false) { Type type = value.GetType(); string name = Enum.GetName(type, value); if (name == null) { return null; } string description = ""; if (dicEnum.TryGetValue(type.FullName+"_"+name,out description)) { return description; } FieldInfo field = type.GetField(name); DescriptionAttribute attribute = Attribute.GetCustomAttribute(field, typeof(DescriptionAttribute)) as DescriptionAttribute; if (attribute == null && isNameInstend == true) { return name; } // if(attribute!=null) { dicEnum[type.FullName + "_" + name] = attribute.Description; } return attribute == null ? null : attribute.Description; } }
這樣就方便獲取所有資訊了,結果類中定義的ErrorMsg不是編碼描述,而是在執行錯誤後的Exception資訊。
這樣一個類似標準的返回結果模板就差不多了。