[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
}
Calling the AsHumanReadable
method will produce
The Base: testing things
AllUrBase: Yes
What do you think about this: It's weird
My users may add SampleClass
objects (or a wide range of other objects implementing SampleBase
) to a shopping cart which will stored for later use.
A customer care worker will be reading the output for checking up on things.
I've thought about making ToString methods (like return "The Base" + BaseProp;
) instead. My frist thought is that the attribute approach is the more flexible one.
What are the pros and cons to those two approaches (maintainance, localization (avoid magic strings when possible) etc.)?