.Net 提供了一个 XmlSerializer 对象,旨在为您提供对象的表示。您可以利用这一点,只需抓取文本节点并加入它们:
public override string ToString()
{
return this.Stringify(); //calls reusable code to "stringify" any object
}
//converts an object's properties to a string of pipe delimited values
public static string Stringify<T>(this T obj)
{
var xs = new XmlSerializer(obj.GetType());
var doc = new XDocument();
using (var writer = doc.CreateWriter())
{
xs.Serialize(writer, obj);
}
var s = from text in doc.XPathSelectElements("//*[./text()]") select text.Value;
return string.Join("|", s);
}
在复杂类的属性上调用 ToString 更复杂......要做到这一点,请在这些属性上使用 XmlElement 属性,以便序列化程序知道您要输出这些属性,然后允许隐式转换为字符串,这样序列化程序就不会出错。奇怪的是,您还需要实现从字符串的隐式转换(我猜是因为序列化程序也具有反序列化的能力);但这不一定有效。非常hacky。
另一种方法是使用属性使您的子类型可序列化[Serializable]
,放置[XmlIgnore]
任何公共属性,然后使用调用 ToString 函数的 get 方法和虚拟 set 方法创建属性(再次欺骗序列化程序)。不是很好,但它有效。
工作示例
using System;
using System.Linq;
using System.Xml.Linq;
using System.Xml.Serialization;
using System.Xml.XPath;
namespace StackOverflow
{
public static class ObjectStringer
{
public static string Stringify<T>(this T obj)
{
var xs = new XmlSerializer(obj.GetType());
var doc = new XDocument();
using (var writer = doc.CreateWriter())
{
xs.Serialize(writer, obj);
}
var s = from text in doc.XPathSelectElements("//*[./text()]") select text.Value;
return string.Join("|", s);
}
}
public class Field
{
static int x = 0;
int y;
public Field()
{
y = ++x;
}
public override string ToString()
{
return y.ToString();
}
public static implicit operator String(Field f)
{
return f==null?null:f.ToString();
}
public static implicit operator Field(String s)
{
return s ?? "nasty hack to make serializer work";
}
}
public class Demo
{
public string P1 { get; set; }
public string X { get; set; } //something to show if we're pulling back results in order defined here, or if the system just goes alphabetically
public string P2 { get; set; }
public int P3 { get; set; }
public DateTime P4 { get; set; }
public Demo P5 { get; set; }
[XmlElement(typeof(String))]
public Field P6 { get; set; }
[XmlElement(typeof(String))]
public Field P7 { get; set; }
public override string ToString()
{
return this.Stringify();
}
}
public class Program
{
public static void Main(string[] args)
{
Demo d = new Demo() { P1 = "test1", X = "expert mode", P2 = "test2", P3 = 3, P4 = DateTime.UtcNow, P5 = new Demo() { P1 = "baby", P2 = "ooh" },P6=new Field(),P7=new Field() };
//d.P5 = d; //this solution's not perfect - e.g. attempt to serialize a circular loop in the object's graph
Console.WriteLine(d.ToString());
Console.WriteLine("done");
Console.ReadKey();
}
}
}
选择
[Serializable]
public class Field
{
static int x = 0;
int y;
public string DummyToString { get { return this.ToString(); } set { /*serializer hack*/ } }
[XmlIgnore]
public string DontShowMe { get; set; }
public Field()
{
y = ++x;
DontShowMe = "you shouldn't see this";
}
public override string ToString()
{
return string.Format("string me on #{0}", y);
}
}
//Demo's Field properties no longer require XmlElement attributes; i.e.:
public Field P6 { get; set; }
public Field P7 { get; set; }
注意:
- 如果您有复杂类型的子项(例如上例中的 P5),您希望如何处理它们?它们的属性是否也应该用管道分隔(在这种情况下,您如何知道哪些属性与哪些对象相关)?
- 应该如何处理空值 - 与空白相同(即两个管道之间没有任何内容),或者根本不输出?
- 返回属性名称和值会更好吗 - 这样您就不会依赖顺序/您的输出对未来类定义的更改更加健壮?
- 也许 XMLSerializer 本身更适合您的基本要求;假设您想要一种表示对象数据的稳健方式?