如何从文件中解析通用数据类型?
我有一个通用类,如下所示:
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 是数字,至少按照惯例
I have a generic class as follows:
class myClass<T>
{
public T[] m_SomeData;
}
I want to implement a generic method to read data from a file and populate the data fields of this class. Something like:
class myClass<T>
{
public T[] m_SomeData;
public void ReadData(string fileName);
}
An implementation of the ReadData methods looks something like this (all error checking removed for brevity):
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
}
Note, I can guarantee the type T is numeric, at least by convention
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
更新:OP想要人类可读的输出。我建议 JavaScriptSerializer,然后,在:
旧答案:
这是 BinaryFormatter:
这当然假设您还使用它通过
formatter.Serialize(fs, m_SomeData);
进行序列化。Update: OP would like human readable output. I would suggest JavaScriptSerializer, then, in:
Old Answer:
This is a job for BinaryFormatter:
This of course assumes you are also using it to serialize via
formatter.Serialize(fs, m_SomeData);
.