日期:2014-05-20  浏览次数:20743 次

想把下面这个函数写成模板。该怎么写啊?
我想把这个函数写成模板,其中TraceServerSettings是一个类,该怎么办?

public static TraceServerSettings Get(string path)
  {
  TraceServerSettings _TraceServerSettings = null;
  if (_TraceServerSettings == null)
  {
  FileStream fs = null;
  try
  {
  XmlSerializer xs = new XmlSerializer(typeof(TraceServerSettings));
  fs = new FileStream(path, FileMode.Open, FileAccess.Read);
  _TraceServerSettings = (TraceServerSettings)xs.Deserialize(fs);
  fs.Close();
  return _TraceServerSettings;
  }
  catch
  {
  if (fs != null)
  fs.Close();
  throw new Exception("Xml deserialization failed!");
  }
  }
  else
  return _TraceServerSettings;
  }

------解决方案--------------------

public static T Get<T>(string path)
{
里面的TraceServerSettings 替换过成T就可以了

_TraceServerSettings = (TraceServerSettings)xs.Deserialize(fs);最好改成
_TraceServerSettings = xs.Deserialize(fs) as T;这样如果不是T类型的,函数返回null,而不是异常
}