如何从文件中解析通用数据类型?

时间:2011-05-23 23:54:01

标签: c# parsing generics

我有一个通用类如下:

class myClass<T>
{
    public T[] m_SomeData;
}

我想实现一个通用方法来从文件中读取数据并填充此类的数据字段。类似的东西:

class myClass<T>
{
    public T[] m_SomeData;

    public void ReadData(string fileName);
}

ReadData方法的实现看起来像这样(为简洁起见,删除了所有错误检查):

void ReadData(string fileName)
{
   TextReader rdr = new StreamReader(fileName);

   string line = rdr.ReadLine();
   // Here I need to parse value of type T from the line
   // and initialize the m_SomeData array  
   // How do I do that? I would like to keep it generic if possible
}

注意,我可以保证类型T是数字,至少按惯例

1 个答案:

答案 0 :(得分:1)

更新: OP希望人类可读输出。我建议使用JavaScriptSerializer,然后在:

  

C:\的Windows \ Microsoft.NET \框架\ v4.0.30319 \ System.Web.Extensions.dll

// Serialize:
using (var fs = new FileStream(fileName, FileMode.Create))
using (var writer = new StreamWriter(fs))
{
    JavaScriptSerializer serializer = new JavaScriptSerializer();
    string s = serializer.Serialize(m_SomeData);                
    writer.Write(s);
}

// Deserialize:
using (var fs = new FileStream(fileName, FileMode.Open))
using (var reader = new StreamReader(fs))
{
    JavaScriptSerializer serializer = new JavaScriptSerializer();
    var s = reader.ReadToEnd();
    m_SomeData = serializer.Deserialize<T[]>(s);                
}

旧答案: 这是BinaryFormatter的工作:

using (FileStream fs = new FileStream(fileName, FileMode.Open)) 
{
    BinaryFormatter formatter = new BinaryFormatter();
    m_SomeData = (T[])formatter.Deserialize(fs);
}

这当然假设您也使用它来通过formatter.Serialize(fs, m_SomeData);序列化。