[在C#中使用IsAssignableFrom()和typeOf(通用)和FileStream

问题描述 投票:0回答:1

我正在尝试编写以下通用反射方法,该方法会自动创建并返回对象的实例:

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我有一个空对象返回

  • c# generic-programming
    1个回答
    0
    投票
    © www.soinside.com 2019 - 2024. All rights reserved.