1 回答

TA貢獻1826條經驗 獲得超6個贊
沒有內置的“純文本”序列化程序將對象屬性值序列化為行分隔文本。大多數時候,當您想要將對象保存為文本時,您只需編寫代碼即可。
例子:
var x = new ResponseGradeDto{
Id = Guid.NewGuid(),
Name = "Foo",
Code = "Cde",
Information = "No info"
};
using (var writer = new StreamWriter(@"C:\temp\log.txt"))
{
writer.WriteLine(x.Name);
writer.WriteLine(x.Code);
writer.WriteLine(x.Information);
}
然而,更通用的方法是使用反射來獲取對象的所有引用屬性:
var properties = typeof(ResponseGradeDto).GetProperties();
然后將屬性轉儲到文件中就很簡單了(注意我使用了x上面代碼中定義的對象):
File.WriteAllLines(@"C:\temp\attr.txt", properties.Select(p => p.GetValue(x).ToString()));
如果您愿意,可以使用帶有上述反射解決方案的屬性來過濾掉想要的/不需要的屬性。在這里,我重用了您在示例中使用的“Xml 屬性”,您可以編寫自己的屬性:
var properties = typeof(ResponseGradeDto).GetProperties().Where(
prop => Attribute.IsDefined(prop, typeof(XmlElementAttribute))
&& !Attribute.IsDefined(prop, typeof(XmlIgnoreAttribute))
);
希望這可以幫助!
- 1 回答
- 0 關注
- 129 瀏覽
添加回答
舉報