将对象类型强制转换为自定义类时发生System.InvalidCastException [英] System.InvalidCastException while casting an object type to custom class

查看:92
本文介绍了将对象类型强制转换为自定义类时发生System.InvalidCastException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

今天在编写代码时,我遇到了一个阶段,我需要将对象类型转换为自定义类,这本来应该很简单,但是我花了好几个小时来解析System.InvalidCastException,最后我最终使用了JsonConvert完成工作.

Today working on my code I came across a phase where i needed to cast an object type to my custom class which should have been very simple, but I ended up hours resolving System.InvalidCastException, finally I ended up using JsonConvert to get the job done.

我不确定是否有更好的方法来解决此问题,如果我想知道我可以做得更好.

I am not really sure if there was a better way to handle this, if there is I would like to know what I could have done better.

给出的是我的自定义类的结构

Given is the structure of my custom class

using SQLite.Net.Attributes;
namespace DataContract
{
public class Event
{
    #region Properties
    [PrimaryKey]
    public int Id { get; set; }

    public string Name { get; set; }

    public DateTime EventDateTime { get; set; }

    #endregion
}
}

Event类位于DataContract共享项目内部,下面给出了该项目的文件夹结构,

The Event class is inside a DataContract shared project and my folder structure of the project is given below,

使用EntityFramework,我从sqlite数据库中获得一个List<Event>,并且我正在使用此列表在android的tableview中显示元素,我一次遍历列表中的一项,然后尝试将其强制转换为我的自定义项活动类.

Using EntityFramework I am getting a List<Event> from my sqlite database and I am using this list to display elements in my tableview for android, I go through one item at a time in my list and try to cast it to my custom Event class.

给出的是我尝试过的相同代码

Given is the code for the same which i tried

//tableItems is my IList<object>
var item = tableItems[position];

        var view = convertView;
        if (view == null)
        {
            view = context.LayoutInflater.Inflate(Resource.Layout.NativeAndroidEventCell, null);
        }


        if (item.GetType().FullName.Equals("DataContract.Event"))
        {
                  var x = item as DataContract.Event; // returns null
                  var y = (DataContract.Event)item; // cast exception
                var z = item.GetType().GetField("Name"); // returns null    

        }

图像中给出了我得到的异常,由于显示为空,所以我在这里看不到堆栈跟踪

The exception I get is given in the image, I am unable to see the stacktrace here as it shows null

当我在控制台中查看item变量的值时,我看到它向我显示了从数据库返回的确切值,甚至在类型列中向我显示了正确的类型,但是由于某些原因,我逐步执行代码,x的值为null.

When I watch the value of item variable in the console I see that it shows me the exact values of what is being returned from the database and it even shows me the correct type in the type column but for some reason when i step through the code the value of x is null.

作为最后的手段,我最终使用了JsonConvert类,并做了类似的事情

As my last resort I ended up using JsonConvert class and did something like this

if (item.GetType().FullName.Equals("DataContract.Event"))
        {
           //Not sure if this is the right approach here but it works
            var serializedObject = JsonConvert.SerializeObject(item, Formatting.Indented);
            var deserializedObject = JsonConvert.DeserializeObject<DataContract.Event>(x);

            view.FindViewById<TextView>(Resource.Id.textView1).Text = deserializedObject.Name;
            view.FindViewById<TextView>(Resource.Id.textView2).Text = deserializedObject.EventDateTime.ToString();
        }

JsonConvert可以工作,而且我能够解决我的问题,但是我更关注的是要知道我是否可以比使用JsonConvert更好地解决此问题,或者我所做的是正确的.请建议

The JsonConvert works and I am able to resolve my issue, but what I am more looking at is to know if I could have done better to resolve this than using JsonConvert Or what I did was correct. Please suggest

推荐答案

经过长时间的研究,我最终使用自己的JSONSerialization方法来处理问题中提到的转换

After long hours of research, I ended up using my own JSONSerialization approach to handle the casting as mentioned in the question

var serializedObject = JsonConvert.SerializeObject(item, Formatting.Indented);
            var deserializedObject = JsonConvert.DeserializeObject<DataContract.Event>(x);

            view.FindViewById<TextView>(Resource.Id.textView1).Text = deserializedObject.Name;
            view.FindViewById<TextView>(Resource.Id.textView2).Text = deserializedObject.EventDateTime.ToString();

这篇关于将对象类型强制转换为自定义类时发生System.InvalidCastException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆