3、代码
using System;
using System.IO;
using System.Collections.Generic;
using System.Reflection;
/* ==============================================================================
* 功能描述:CSV(逗号分割文件)解析器
* ==============================================================================*/
public class CsvParser{
public delegate T Parser<T>(List<string> lineFields);
/// <summary>
/// 转换
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="colNames"></param>
/// <param name="fieldValues"></param>
/// <param name="type"></param>
/// <returns></returns>
public static T ReflectionParser<T>(string[] colNames, string[] fieldValues, Type type){
//使用指定类型的默认构造函数来创建该类型的实例
T t = (T)System.Activator.CreateInstance(type);
for(int i=0; i<colNames.Length; i++){
//#if UNITY_EDITOR
try{
//#endif
if (colNames == null)
{
continue;
}
PropertyInfo property = t.GetType().GetProperty(colNames);
if (string.IsNullOrEmpty(fieldValues))
{
Type propertyType = property.PropertyType;
if (propertyType == typeof(string))
{
property.SetValue(t, "", null);
}
else if (propertyType == typeof(int) || propertyType == typeof(short) ||
propertyType == typeof(byte) || propertyType == typeof(float) ||
propertyType == typeof(double))
{
property.SetValue(t, 0, null);
}
else
{
UnityEngine.Debug.Log("Can not found default value for " + propertyType);
}
}
else
{
property.SetValue(t, Convert.ChangeType(fieldValues, property.PropertyType), null);
}
//#if UNITY_EDITOR
}catch(Exception e){
Debuger.Log("Error at parse for `" + typeof(T) + "` column index=" + i + ", column name=" + colNames + ", value=" + fieldValues + " value in #0 column=" + fieldValues[0] + ", error=" + e);
}
//#endif
}
return t;
}
public static List<T> DoParseByReader<T>(char fieldSeparator, char fieldBound, StreamReader reader, Parser<T> parser){
string line = null;
List<T> list = new List<T>();
那么定义一个ConfigErrorCode的类(类名不用和文件名一样,你可以随便取)
/* ==============================================================================
* 功能描述:错误码
* ==============================================================================*/
public class ConfigErrorCode{
/// <summary>
/// 错误的id
/// </summary>
public int id{get; set;}
/// <summary>
/// 错误的提示信息
/// </summary>
public string text{get; set;}
}
解析代码:
string content = (Resources.Load("ConfigErrorCode") as TextAsset).text;
List<ConfigErrorCode> configError = CsvParser.DoParseByFileContent<ConfigErrorCode>(typeof(ConfigErrorCode), new string[] {
"id",
"text"
}, content);
没错,这样就可以获得一个错误码的列表了~如果你想要获得的是Dictionary。那么自行处理即可~ 作者: ZackD 时间: 2015-2-5 22:10
代码可以不要用斜体吗。。作者: HIDEOKOJIMA 时间: 2015-2-5 22:23
Thanks for sharing this one !作者: hariboot 时间: 2015-2-5 23:58
代码可以不要用斜体吗作者: myonkyo 时间: 2015-2-8 13:19
感谢分享,谢谢提供下载