0
我試圖找到一種簡單的方法來序列化任何對象,以便只包含即時屬性及其「ToString」值。在來自DataContext的對象的情況下,我希望能夠忽略屬性的屬性(即,如果某個屬性是一個複雜的對象,請不要序列化該對象)。這是特別重要的,如果沒有加載屬性,因爲它會導致錯誤「不能訪問一個對象後,已被處置」...序列化後的Linq2Sql對象
我創建了以下,但它嘗試訪問wasn' t加載到原始的datacontext調用中。
string typeString = o.GetType().Name;
StringBuilder xml = new StringBuilder();
xml.AppendFormat("<{0}>\r\n", typeString);
foreach (PropertyInfo property in o.GetType().GetProperties())
{
var propertyValue = property.GetValue(o, null);
if (property.GetType() != typeof(System.Data.Linq.Binary) && property.PropertyType.Name != "EntitySet`1" && property.GetCustomAttributes(typeof(XmlIgnoreAttribute), true).Count() == 0)
{
xml.AppendFormat("<{0}>{1}</{0}>\r\n", property.Name, propertyValue);
}
}
xml.AppendFormat("</{0}>", typeString);
return xml.ToString();
我希望避免與「IgnoreDataMember」標籤類。基本上我想要一個我傳遞給它的對象的快照,那麼我將如何去使用PropertyType來過濾掉「複雜類型」,我需要說type = int,string還是.. etc? – 2013-03-20 23:40:20
相應地更新了答案。 – 2013-03-20 23:47:41
這太好了。它也修復了datacontext問題,儘管理想情況下我仍然可以使用「ToString」顯示覆雜類型的「加載」屬性。但我會拿我能得到的。 – 2013-03-21 00:29:07