显示对象的内容

时间:2012-06-26 14:36:15

标签: c# reflection localization

[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;)。我的首要想法是属性方法更灵活。

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

1 个答案:

答案 0 :(得分:3)

我建议删除自定义实现并查看ServiceStack.Text,特别是T.Dump方法。

这已经实施并且可靠。它没有涉及的唯一事情是友好的布尔字符串(是/否)/。

自定义实现涉及首先创建一个良好且有效的解决方案,这需要时间,然后维护并添加对新内容的支持,这也需要时间。 有许多方法可以做到这一点,属性就是其中之一,但是当你拥有ServiceStack时,它根本不值得。

最终,您可以修改T.Dump方法并根据您的要求对其进行自定义。它仍然不是从头开始的。