简体   繁体   English

查找对象属性(反射)的困难

[英]The Difficulty of finding the object properties (reflection)

I wrote a program that does work with files like delete and update, store, and search And all customers But I have a problem with the method is Deserialize 我写了一个程序,该程序可以处理诸如删除和更新,存储和搜索之类的文件。所有客户,但是我对方法有疑问是反序列化

I want the tab grid (Customer Grid ) when I click on any row in order to be seen for a specific customer. 我希望在单击任何行时都可以使用选项卡网格(Customer Grid),以便可以看到特定客户。

But I think the main problem is in this line, this line is Deseriailize method. 但我认为主要问题在于此行,此行是反序列化方法。

var objProps = obj.GetType().GetProperties();

Because the code does not get the object properties properly 因为代码无法正确获取对象属性

Project Files 项目文件

Please see the video 请看视频

 public T Deserialize<T>(string entity)
    {
        var obj = Activator.CreateInstance<T>();
        var stringProps = entity.Split(',');
        var objProps = obj.GetType().GetProperties();

        var propIndex = 0;

        for (int i = 0; i < stringProps.Length; i++)
        {
            try
            {
                if (objProps[propIndex].PropertyType.FullName == "System.String")
                {
                    objProps[propIndex].SetValue(obj, stringProps[i], null);
                }
                else if (objProps[propIndex].PropertyType.FullName == "System.Int32")
                {
                    objProps[propIndex].SetValue(obj, Convert.ToInt32(stringProps[i]), null);
                }
                else if (objProps[propIndex].PropertyType.FullName == "System.DateTime")
                {
                    var cultureInfo = new CultureInfo("fa-IR");
                    DateTime dateTime = Convert.ToDateTime(stringProps[i], cultureInfo);
                    objProps[propIndex].SetValue(obj, dateTime, null);
                }
                else
                {
                    i--;
                }
                propIndex++;
            }

            catch (IndexOutOfRangeException)
            {
                Debug.WriteLine("Index Out Of range");
            }
        }
        return obj;
    }

Your problem is that you are calling Serializer.Deserialize<List<T>>(line) hence GetProperties() returns properties of List<T> , not T itself. 您的问题是您正在调用Serializer.Deserialize<List<T>>(line)因此GetProperties()返回List<T>属性,而不是T本身。 They are: 他们是:

  • Int32 Capacity
  • Int32 Count
  • OrderItem Int32

so what is your code trying to execute is to assign stringProps[i] with value 30/1/2008 to Int32 Count property. 因此,您要执行的代码是将值30/1/2008 stringProps[i]分配给Int32 Count属性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM