如何通过函数重载方法传递不同类的不同对象?
示例代码:
static public void SerializeToXML(Movie movie)
{
XmlSerializer serializer = new XmlSerializer(typeof(Movie));
TextWriter textWriter = new StreamWriter(@"C:\movie.xml");
serializer.Serialize(textWriter, movie);
textWriter.Close();
}
当我使用此代码时:
static public void SerializeToXML(FbTextView p, FbTextField q)
{
try
{
XmlSerializer textviewserilizer = new XmlSerializer(typeof(FbTextView));
XmlSerializer textfieldserilizer = new XmlSerializer(typeof(FbTextField));
TextWriter textWriter = new StreamWriter(@"D:\movie.xml");
textviewserilizer.Serialize(textWriter, p);
textfieldserilizer.Serialize(textWriter, q);
textWriter.Close();
}
catch (Exception ex)
{
while (ex != null)
{
Trace.WriteLine(ex.Message);
ex = ex.InnerException;
MessageBox.Show(ex.Message);
}
throw;
}
}
其输出xml显示一些结果:
XML Parsing Error: junk after document element
Location: file:///D:/movie.xml
Line Number 6, Column 14:</FbTextView><?xml version="1.0" encoding="utf-8"?>
-------------^
答案 0 :(得分:6)
你可以使用generics
:
public static void SerializeToXml<T>(this T objectToSerialize, string fileName)
{
XmlSerializer serializer = new XmlSerializer(objectToSerialize.GetType());
using (TextWriter textWriter = new StreamWriter(fileName))
{
serializer.Serialize(textWriter, objectToSerialize);
}
}
constrain
只接受某些类型。using statement
extension method
。 如果您使用SerializeToXml方法作为扩展方法,可以通过以下两种方式之一调用它,结果将是相同的:
movie.SerializeToXml(@"C:\movie.xml");
SerializeToXml(movie, @"C:\movie.xml");
答案 1 :(得分:3)
这里可以使用扩展方法
var xml = movie.SerializeToXML();
public static class SOExtensions
{
public static string SerializeToXML<T>(this T obj) where T : new()
{
StringWriter s = new StringWriter();
XmlSerializer serializer = new XmlSerializer(typeof(T));
serializer.Serialize(s, obj);
return s.ToString();
}
}
对于@ JohnSaunders'评论:“ - 1,直到您将StringWriter放入使用块”
“StringWriter Class”实现TextWriter以将信息写入字符串。信息存储在基础 StringBuilder 中。 http://msdn.microsoft.com/en-us/library/system.io.stringwriter.aspx
以下是StringWriter的代码及其基类dispose。
//StringWriter
protected override void Dispose(bool disposing)
{
this._isOpen = false;
base.Dispose(disposing);
}
//TextWriter
protected virtual void Dispose(bool disposing)
{
}