gpt4 book ai didi

c# - 显示对象的内容

转载 作者:行者123 更新时间:2023-11-30 22:27:37 27 4
gpt4 key购买 nike

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

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

最佳答案

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

它已经实现并且可靠。它唯一没有涵盖的是友好的 bool 字符串 (Yes/No)/。

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

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

关于c# - 显示对象的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11209765/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com