如题。在MSDN里,里面的某些源码的某些类都是对某些类的某些成员进行了特性的描述。如下MSDN源码:using System;
using System.Xml;
using System.Xml.Serialization;
using System.IO;/* The XmlRootAttribute allows you to set an alternate name
(PurchaseOrder) of the XML element, the element namespace; by
default, the XmlSerializer uses the class name. The attribute
also allows you to set the XML namespace for the element. Lastly,
the attribute sets the IsNullable property, which specifies whether
the xsi:null attribute appears if the class instance is set to
a null reference. */
[XmlRootAttribute("PurchaseOrder", Namespace = "http://www.cpandl.com",
IsNullable = false)]//这些地方都是对成员特性描述了。才可以在XML序列化时上用。不用XML序列化就起不了作用,那要是我想对某个DLL内的某个类序列化。而这时,我根本就不知道该DLL内的这个类的成员是的特性是怎么样描述的。我可以将期序列化吗?或是没有其它更好的方法呢?
public class PurchaseOrder
{
public Address ShipTo;
public string OrderDate;
/* The XmlArrayAttribute changes the XML element name
from the default of "OrderedItems" to "Items". */
[XmlArrayAttribute("Items")]//这些地方都是对成员特性描述了。
public OrderedItem[] OrderedItems;
public decimal SubTotal;
public decimal ShipCost;
public decimal TotalCost;
}public class Address
{
/* The XmlAttribute instructs the XmlSerializer to serialize the Name
field as an XML attribute instead of an XML element (the default
behavior). */
[XmlAttribute]//这些地方都是对成员特性描述了。
public string Name;
public string Line1; /* Setting the IsNullable property to false instructs the
XmlSerializer that the XML attribute will not appear if
the City field is set to a null reference. */
[XmlElementAttribute(IsNullable = false)]//这些地方都是对成员特性描述了。
public string City;
public string State;
public string Zip;
}public class OrderedItem
{
public string ItemName;
public string Description;
public decimal UnitPrice;
public int Quantity;
public decimal LineTotal; /* Calculate is a custom method that calculates the price per item,
and stores the value in a field. */
public void Calculate()
{
LineTotal = UnitPrice * Quantity;
}
}public class Test
{
public static void Main()
{
// Read and write purchase orders.
Test t = new Test();
t.CreatePO("po.xml");
t.ReadPO("po.xml"); Console.ReadKey();
} private void CreatePO(string filename)
{
// Create an instance of the XmlSerializer class;
// specify the type of object to serialize.
XmlSerializer serializer =
new XmlSerializer(typeof(PurchaseOrder));
TextWriter writer = new StreamWriter(filename);
PurchaseOrder po = new PurchaseOrder(); // Create an address to ship and bill to.
Address billAddress = new Address();
billAddress.Name = "Teresa Atkinson";
billAddress.Line1 = "1 Main St.";
billAddress.City = "AnyTown";
billAddress.State = "WA";
billAddress.Zip = "00000";
// Set ShipTo and BillTo to the same addressee.
po.ShipTo = billAddress;
po.OrderDate = System.DateTime.Now.ToLongDateString(); // Create an OrderedItem object.
OrderedItem i1 = new OrderedItem();
i1.ItemName = "Widget S";
i1.Description = "Small widget";
i1.UnitPrice = (decimal)5.23;
i1.Quantity = 3;
i1.Calculate(); // Insert the item into the array.
OrderedItem[] items = { i1 };
po.OrderedItems = items;
// Calculate the total cost.
decimal subTotal = new decimal();
foreach (OrderedItem oi in items)
{
subTotal += oi.LineTotal;
}
po.SubTotal = subTotal;
po.ShipCost = (decimal)12.51;
po.TotalCost = po.SubTotal + po.ShipCost;
// Serialize the purchase order, and close the TextWriter.
serializer.Serialize(writer, po);
writer.Close();
} protected void ReadPO(string filename)
{
// Create an instance of the XmlSerializer class;
// specify the type of object to be deserialized.
XmlSerializer serializer = new XmlSerializer(typeof(PurchaseOrder));
/* If the XML document has been altered with unknown
nodes or attributes, handle them with the
UnknownNode and UnknownAttribute events.*/
serializer.UnknownNode += new
XmlNodeEventHandler(serializer_UnknownNode);
serializer.UnknownAttribute += new
XmlAttributeEventHandler(serializer_UnknownAttribute); // A FileStream is needed to read the XML document.
FileStream fs = new FileStream(filename, FileMode.Open);
// Declare an object variable of the type to be deserialized.
PurchaseOrder po;
/* Use the Deserialize method to restore the object's state with
data from the XML document. */
po = (PurchaseOrder)serializer.Deserialize(fs);
// Read the order date.
Console.WriteLine("OrderDate: " + po.OrderDate); // Read the shipping address.
Address shipTo = po.ShipTo;
ReadAddress(shipTo, "Ship To:");
// Read the list of ordered items.
OrderedItem[] items = po.OrderedItems;
Console.WriteLine("Items to be shipped:");
foreach (OrderedItem oi in items)
{
Console.WriteLine("\t" +
oi.ItemName + "\t" +
oi.Description + "\t" +
oi.UnitPrice + "\t" +
oi.Quantity + "\t" +
oi.LineTotal);
}
// Read the subtotal, shipping cost, and total cost.
Console.WriteLine("\t\t\t\t\t Subtotal\t" + po.SubTotal);
Console.WriteLine("\t\t\t\t\t Shipping\t" + po.ShipCost);
Console.WriteLine("\t\t\t\t\t Total\t\t" + po.TotalCost);
} protected void ReadAddress(Address a, string label)
{
// Read the fields of the Address object.
Console.WriteLine(label);
Console.WriteLine("\t" + a.Name);
Console.WriteLine("\t" + a.Line1);
Console.WriteLine("\t" + a.City);
Console.WriteLine("\t" + a.State);
Console.WriteLine("\t" + a.Zip);
Console.WriteLine();
} private void serializer_UnknownNode
(object sender, XmlNodeEventArgs e)
{
Console.WriteLine("Unknown Node:" + e.Name + "\t" + e.Text);
} private void serializer_UnknownAttribute
(object sender, XmlAttributeEventArgs e)
{
System.Xml.XmlAttribute attr = e.Attr;
Console.WriteLine("Unknown attribute " +
attr.Name + "='" + attr.Value + "'");
}
}
如果我想序列化/反序列化某个DLL内的某个类,我该怎么做。
using System.Xml;
using System.Xml.Serialization;
using System.IO;/* The XmlRootAttribute allows you to set an alternate name
(PurchaseOrder) of the XML element, the element namespace; by
default, the XmlSerializer uses the class name. The attribute
also allows you to set the XML namespace for the element. Lastly,
the attribute sets the IsNullable property, which specifies whether
the xsi:null attribute appears if the class instance is set to
a null reference. */
[XmlRootAttribute("PurchaseOrder", Namespace = "http://www.cpandl.com",
IsNullable = false)]//这些地方都是对成员特性描述了。才可以在XML序列化时上用。不用XML序列化就起不了作用,那要是我想对某个DLL内的某个类序列化。而这时,我根本就不知道该DLL内的这个类的成员是的特性是怎么样描述的。我可以将期序列化吗?或是没有其它更好的方法呢?
public class PurchaseOrder
{
public Address ShipTo;
public string OrderDate;
/* The XmlArrayAttribute changes the XML element name
from the default of "OrderedItems" to "Items". */
[XmlArrayAttribute("Items")]//这些地方都是对成员特性描述了。
public OrderedItem[] OrderedItems;
public decimal SubTotal;
public decimal ShipCost;
public decimal TotalCost;
}public class Address
{
/* The XmlAttribute instructs the XmlSerializer to serialize the Name
field as an XML attribute instead of an XML element (the default
behavior). */
[XmlAttribute]//这些地方都是对成员特性描述了。
public string Name;
public string Line1; /* Setting the IsNullable property to false instructs the
XmlSerializer that the XML attribute will not appear if
the City field is set to a null reference. */
[XmlElementAttribute(IsNullable = false)]//这些地方都是对成员特性描述了。
public string City;
public string State;
public string Zip;
}public class OrderedItem
{
public string ItemName;
public string Description;
public decimal UnitPrice;
public int Quantity;
public decimal LineTotal; /* Calculate is a custom method that calculates the price per item,
and stores the value in a field. */
public void Calculate()
{
LineTotal = UnitPrice * Quantity;
}
}public class Test
{
public static void Main()
{
// Read and write purchase orders.
Test t = new Test();
t.CreatePO("po.xml");
t.ReadPO("po.xml"); Console.ReadKey();
} private void CreatePO(string filename)
{
// Create an instance of the XmlSerializer class;
// specify the type of object to serialize.
XmlSerializer serializer =
new XmlSerializer(typeof(PurchaseOrder));
TextWriter writer = new StreamWriter(filename);
PurchaseOrder po = new PurchaseOrder(); // Create an address to ship and bill to.
Address billAddress = new Address();
billAddress.Name = "Teresa Atkinson";
billAddress.Line1 = "1 Main St.";
billAddress.City = "AnyTown";
billAddress.State = "WA";
billAddress.Zip = "00000";
// Set ShipTo and BillTo to the same addressee.
po.ShipTo = billAddress;
po.OrderDate = System.DateTime.Now.ToLongDateString(); // Create an OrderedItem object.
OrderedItem i1 = new OrderedItem();
i1.ItemName = "Widget S";
i1.Description = "Small widget";
i1.UnitPrice = (decimal)5.23;
i1.Quantity = 3;
i1.Calculate(); // Insert the item into the array.
OrderedItem[] items = { i1 };
po.OrderedItems = items;
// Calculate the total cost.
decimal subTotal = new decimal();
foreach (OrderedItem oi in items)
{
subTotal += oi.LineTotal;
}
po.SubTotal = subTotal;
po.ShipCost = (decimal)12.51;
po.TotalCost = po.SubTotal + po.ShipCost;
// Serialize the purchase order, and close the TextWriter.
serializer.Serialize(writer, po);
writer.Close();
} protected void ReadPO(string filename)
{
// Create an instance of the XmlSerializer class;
// specify the type of object to be deserialized.
XmlSerializer serializer = new XmlSerializer(typeof(PurchaseOrder));
/* If the XML document has been altered with unknown
nodes or attributes, handle them with the
UnknownNode and UnknownAttribute events.*/
serializer.UnknownNode += new
XmlNodeEventHandler(serializer_UnknownNode);
serializer.UnknownAttribute += new
XmlAttributeEventHandler(serializer_UnknownAttribute); // A FileStream is needed to read the XML document.
FileStream fs = new FileStream(filename, FileMode.Open);
// Declare an object variable of the type to be deserialized.
PurchaseOrder po;
/* Use the Deserialize method to restore the object's state with
data from the XML document. */
po = (PurchaseOrder)serializer.Deserialize(fs);
// Read the order date.
Console.WriteLine("OrderDate: " + po.OrderDate); // Read the shipping address.
Address shipTo = po.ShipTo;
ReadAddress(shipTo, "Ship To:");
// Read the list of ordered items.
OrderedItem[] items = po.OrderedItems;
Console.WriteLine("Items to be shipped:");
foreach (OrderedItem oi in items)
{
Console.WriteLine("\t" +
oi.ItemName + "\t" +
oi.Description + "\t" +
oi.UnitPrice + "\t" +
oi.Quantity + "\t" +
oi.LineTotal);
}
// Read the subtotal, shipping cost, and total cost.
Console.WriteLine("\t\t\t\t\t Subtotal\t" + po.SubTotal);
Console.WriteLine("\t\t\t\t\t Shipping\t" + po.ShipCost);
Console.WriteLine("\t\t\t\t\t Total\t\t" + po.TotalCost);
} protected void ReadAddress(Address a, string label)
{
// Read the fields of the Address object.
Console.WriteLine(label);
Console.WriteLine("\t" + a.Name);
Console.WriteLine("\t" + a.Line1);
Console.WriteLine("\t" + a.City);
Console.WriteLine("\t" + a.State);
Console.WriteLine("\t" + a.Zip);
Console.WriteLine();
} private void serializer_UnknownNode
(object sender, XmlNodeEventArgs e)
{
Console.WriteLine("Unknown Node:" + e.Name + "\t" + e.Text);
} private void serializer_UnknownAttribute
(object sender, XmlAttributeEventArgs e)
{
System.Xml.XmlAttribute attr = e.Attr;
Console.WriteLine("Unknown attribute " +
attr.Name + "='" + attr.Value + "'");
}
}
如果我想序列化/反序列化某个DLL内的某个类,我该怎么做。
解决方案 »
- amCharts 控件问题清除Title(急)
- C# 同一个窗体只能弹出一次(不是子父级窗口)也不是ShowDialog有其他方法吗?
- C#如何在运行的时候找到一个对象的所有的引用,即引用这个对象的所有的对象
- wpf开发风险大不大,能向下兼容吗,例如XP那个慢。。。
- 对数据库中的数据进行修改
- 请问有没有办法实现文字和图片一起上传到数据库, 显示的时候一起显示(急)
- 在C#.NET中为什么没有DataTimeBox控件呀?如何加上?
- 关于Com interop的问题
- 关于DataGrid控件的非常具有挑战性问题,分数不够再加,
- 这里有c#编译器
- DrawCurve为何画出怪异的曲线
- 如何取得SQL过程返回值
public class TestClass
{
private int a;
private string b; public int A
{
get { return a; }
set { a = value; }
} public string B
{
get { return b; }
set { b = value; }
}
}序列化它:
TestClass test = new TestClass();
test.A = 100;
test.B = "abc";
XmlSerializer xs = new XmlSerializer(test.GetType()); XmlWriter xw = new XmlTextWriter("c:\\test.xml", Encoding.UTF8);
xs.Serialize(xw, test);
大哥,就差一个DeSerialize的代码。继续下去。
不是所有类都可以XML序列化。刚刚编译出错看到了。如果你序列化某个对象时,要看看这个对象所属的类,是否有无:无参数构造函数。XML序列化的对象一定要有:无参数构造函数。
这样也不行的。你自己写的类继承你要XML序列化的对象的类。当代码调用了你自己写的这个类的构造函数时,那也会相应调用父类同参数的构造器。//这时就是出一样的错误。那归根到底还是会调用到你自己写的类的父类的构造函数。