2
[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;)。我的第一个想法是属性方法更灵活。

这两种方法(维护、本地化(尽可能避免使用魔法字符串)等)的优缺点是什么?

4

1 回答 1

3

我建议放弃自定义实现并查看ServiceStack.Text,尤其是T.Dump方法。

这是已经实现且可靠的东西。它唯一没有涵盖的是友好的布尔字符串(是/否)/。

自定义实现首先需要创建一个良好且有效的解决方案,这需要时间,然后是维护和添加对新东西的支持,这也需要时间。有很多方法可以做到这一点,属性就是其中之一,但是当你拥有ServiceStack.

最终,您可以修改 T.Dump 方法并自定义它们以满足您的要求。它仍然不是从头开始的东西。

于 2012-06-26T14:43:18.570 回答