[Serializable]
public class SampleBase
{
[HumanReadableAttribute("The Base")]
public string BaseProp { get; set; } // "testing things"
public bool AllUrBase { get; set; } // true
public string AsHumanReadable()
{
var type = GetType();
var properties = type.GetProperties();
var stringRepresentation = new List<string>();
foreach (var p in properties)
{
var ca = p.GetCustomAttributes(true).FirstOrDefault(a => a is HumanReadableAttribute);
var v = p.GetValue(this, null);
var t = v.GetType();
var e = t.IsEnum ? t.GetField(Enum.GetName(t, v)).GetCustomAttributes(typeof(HumanReadableAttribute), false).FirstOrDefault() as HumanReadableAttribute : null;
stringRepresentation.Add(string.Format("{0}: {1}", ca ?? p.Name, v is bool ? ((bool) v ? "Yes" : "No") : e ?? v));
}
return string.Join("\r\n", stringRepresentation);
}
}
[Serializable]
public class SampleClass {
public enum MyEnum {
[HumanReadableAttribute("It makes sense")]
MakesSense,
[HumanReadableAttribute("It's weird")]
Nonsense
}
[HumanReadableAttribute("What do you think about this")]
public MyEnum MyProperty { get; set; } // Nonsense
}
调用AsHumanReadable
方法会产生
The Base: testing things
AllUrBase: Yes
What do you think about this: It's weird
我的用户可以将SampleClass
对象(或实现的各种其他对象SampleBase
)添加到购物车,该购物车将被存储以备后用。客户服务人员将阅读输出以检查事情。
我考虑过制作 ToString 方法(如return "The Base" + BaseProp;
)。我的第一个想法是属性方法更灵活。
这两种方法(维护、本地化(尽可能避免使用魔法字符串)等)的优缺点是什么?