C# 概括一个方法来处理各种对象
在我正在编写的一个程序中,我决定使用我自己的数据类型,而不是出于教育目的使用任何其他数据库 数据保存为csv文件,我有一种方法可以将.csv转换为简单字符串[,] 每个类X作为它自己的字符串[,]来列出转换器。 在前3节课之后,我开始玩泛型和反射。 我确实成功地将一个常规列表转换为字符串[,],但是做相反的事情看起来很困难 我将列表实现为字符串[,]的方式是:C# 概括一个方法来处理各种对象,c#,visual-studio-2008,reflection,casting,C#,Visual Studio 2008,Reflection,Casting,在我正在编写的一个程序中,我决定使用我自己的数据类型,而不是出于教育目的使用任何其他数据库 数据保存为csv文件,我有一种方法可以将.csv转换为简单字符串[,] 每个类X作为它自己的字符串[,]来列出转换器。 在前3节课之后,我开始玩泛型和反射。 我确实成功地将一个常规列表转换为字符串[,],但是做相反的事情看起来很困难 我将列表实现为字符串[,]的方式是: public string[,] ToArray(object[] sender) { if (sender.L
public string[,] ToArray(object[] sender)
{
if (sender.Length==0)
{
return null;
}
string[,] ret;
PropertyInfo[] props;
if (sender.Length > 0)
{
props = sender[0].GetType().GetProperties();
ret = new string[props.Length, sender.Length];
}
else
{
return null;
}
for (int i=0;i<sender.Length;i++)
{
for (int p = 0; p < props.Length; p++)
{
object value=props[p].GetValue(sender[i], null);
if (value!=null) ret[p, i] = value.ToString();
}
}
return ret;
}
对于类Windows字符串名称,双尺寸,布尔盲板
我通常将数组[,]转换为Windows,如下所示:
public static List<Windows> ToList(string[,] arra)
{
List<Windows> ret = new List<Windows>(); // change Windows to anything
int col = array.GetLength(1);
int row = array.GetLength(0);
PropertyInfo[] props=PropArray(new Windows());
int propslen=props.Length;
for (int c = 0; c < col; c++)
{
Windows entry=new Windows();
for (int r = 0; r < propslen; r++)
{
Type pt = props[r].PropertyType;
if (pt==typeof(string))
props[r].SetValue(entry,array[r,c],null);
else
if (pt==typeof(int))
{
int i=0;int.TryParse(array[r,c],out i);
props[r].SetValue(entry,i,null);
}
else
if (pt==typeof(bool))
{
bool i = false; bool.TryParse(array[r, c], out i);
props[r].SetValue(entry,i,null);
}
else
if (pt == typeof(double))
{
double i = 0; double.TryParse(array[r, c], out i);
props[r].SetValue(entry, i, null);
}
else
if (pt==typeof(DateTime))
{
DateTime i = DateTime.MinValue; DateTime.TryParse(array[r, c], out i);
props[r].SetValue(entry,i,null);
}
}
ret.Add(entry);
}
return ret;
}
我所需要做的就是将Windows这个词替换为任何其他数据类型,它就可以工作了
真正的问题是,我如何将它推广到接收一个类型,并单独列出所有实例
有可能吗
提前感谢,,
加布里埃尔我不会万无一失,但你可以使用泛型。比如:
public static List<T> ToList<T>(string[,] arra) // T can be anything
where T : new() // as long as it has a default constructor
{
List<T> ret = new List<T>();
int col = array.GetLength(1);
int row = array.GetLength(0);
PropertyInfo[] props=PropArray(new T());
int propslen=props.Length;
for (int c = 0; c < col; c++)
{
T entry=new T();
// ...
您所做的本质上是一种序列化格式。如果对象是没有复杂引用的值,则序列化格式相对简单。简单xml或json是常见的格式。也许您应该研究一下如何使用json 如果您选择自己的roll,为什么不尝试使用属性名作为键呢?在键/值列表前面加上类名,并在反序列化时实例化对象。示例格式
MyApplication.Person, MyAssembly
Name=Steve
Age=30
MyApplication.Person, MyAssembly
Name=Bob
Age=54
要进行反序列化,请读取类名,然后使用FormatterServices.GetUninitializedObject安装以获取该类的空实例。然后使用该类的属性信息,设置文件中后面的键/值对中的值。这本质上是一种简化的JSON表示法,不支持列表、映射等。感谢各位,Anders提供了一个新的视角,现在改变已经太晚了,但总有新的项目:]。我在寻找答案!