我正在尝试编写以下通用反射方法,该方法会自动创建并返回对象的实例:
public T Loader<T>(StreamReader sr) where T : new()
{
T ob = default(T);
Type tob = null;
PropertyInfo property = null;
while (!sr.EndOfStream)
{
var line = sr.ReadLine();
if (line == "[[]]")
return ob;
else if (line.StartsWith("[["))
{
tob = Type.GetType(line.Trim('[', ']'));
if (typeof(T).IsAssignableFrom(tob)) // Student == Student
ob = (T)Activator.CreateInstance(tob);
}
else if (line.StartsWith("[") && ob != null)
property = tob.GetProperty(line.Trim('[', ']'));
else if (ob != null && property != null)
property.SetValue(ob, Convert.ChangeType(line, property.PropertyType));
}
return default;
}
基于TXT DATA。档案格式:
[[Student]]
[Name]
Jan
[Surname]
Budalski
[Faculty]
WIMiI
[NrIndeksu]
1013
[[]]
...
an so on
调用方法:
FileStream fs = new FileStream("dane.txt", FileMode.Open);
StreamReader sr = new StreamReader(fs);
Student student = iOHelper.Loader<Student>(sr);
对于C#读者,我有几个[[问题:
False
使用IDE调试的PS假值
P.S.S我有一个空对象返回