Is there any problem when generic type parameter and non-generic type parameter are both used in a function?

  • Thread starter Thread starter E-John
  • Start date Start date
E

E-John

Guest
Dear All,

How can I serialize a List<> of classes that I've created

I found a code snippet from website,

Is there any problem if the parameter is extended to generic type parameter and none-generic type parameter, like below,

From document below, it seems no body use generic type parameter and non-generic type parameter,

泛型型別參數 (C# 程式設計手冊)


Thanks and Best regards,

E-John

public void Serialize<T>(T data, string fileName)
{
// Use a file stream here.
using (TextWriter WriteFileStream = new StreamWriter(fileName))
{
// Construct a SoapFormatter and use it
// to serialize the data to the stream.
XmlSerializer SerializerObj = new XmlSerializer(typeof(T));

try
{
// Serialize EmployeeList to the file stream
SerializerObj.Serialize(WriteFileStream, data);
}
catch (Exception ex)
{
Console.WriteLine(string.Format("Failed to serialize. Reason: {0}", ex.Message));
}
}
}

public T Deserialize<T>(string fileName) where T : new()
{
//List<Employee> EmployeeList2 = new List<Employee>();
// Create an instance of T
T ReturnListOfT = CreateInstance<T>();

// Create a new file stream for reading the XML file
using (FileStream ReadFileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read))
{
// Construct a XmlSerializer and use it
// to serialize the data from the stream.
XmlSerializer SerializerObj = new XmlSerializer(typeof(T));
try
{
// Deserialize the hashtable from the file
ReturnListOfT = (T)SerializerObj.Deserialize(ReadFileStream);
}
catch (Exception ex)
{
Console.WriteLine(string.Format("Failed to serialize. Reason: {0}", ex.Message));
}

}
// return the Deserialized data.
return ReturnListOfT;
}

// function to create instance of T
public static T CreateInstance<T>() where T : new()
{
return (T)Activator.CreateInstance(typeof(T));
}

Continue reading...
 
Back
Top