Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/24.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C#强制转换枚举InvalidCastException错误_C#_.net_Sqlite_Casting_Enums - Fatal编程技术网

C#强制转换枚举InvalidCastException错误

C#强制转换枚举InvalidCastException错误,c#,.net,sqlite,casting,enums,C#,.net,Sqlite,Casting,Enums,所以我有一个使用Firebird的旧代码,我从那里获取了代码,因为它工作得很好,但在这里它没有。给了我一个无效的例外 那么我在努力什么呢 animal.FeedScheduleType = (BcFeedScheduleType)drAnimal["feedschedule_type"]; 所以我试着从我的数据表中提取一些东西,并将其放在animal.FeedScheduleType中。现在我的cast指向一个公共枚举 public enum BcFeedScheduleType {

所以我有一个使用Firebird的旧代码,我从那里获取了代码,因为它工作得很好,但在这里它没有。给了我一个无效的例外

那么我在努力什么呢

animal.FeedScheduleType = (BcFeedScheduleType)drAnimal["feedschedule_type"];
所以我试着从我的数据表中提取一些东西,并将其放在animal.FeedScheduleType中。现在我的cast指向一个公共枚举

    public enum BcFeedScheduleType
{
    Default = 0,
    FromList = 1,
    Group = 2
}
和animal.FeedScheduleType是

private BcFeedScheduleType _feedScheduleType;

public BcFeedScheduleType FeedScheduleType
    {
        get { return _feedScheduleType; }
        set { _feedScheduleType = value; }
    }
但每当它点击这个,它就会抛出一个InvalidCastException错误,我不知道为什么,我在这里和谷歌搜索了一下,但找不到任何关于这类演员的信息


编辑:数据库中的类型是整数

您是否尝试先强制转换为int

animal.FeedScheduleType = (BcFeedScheduleType)(int)drAnimal["feedschedule_type"];
试试这个:

animal.FeedScheduleType = (BcFeedScheduleType)Convert.ToInt32(drAnimal["feedschedule_type"]);

这是一个。

我猜您的drAnimal返回的是字符串而不是int。如果是这种情况,那么

animal.FeedScheduleType=(BcFeedScheduleType)Int.Parse(drAnimal[“FeedScheduleType”)

如果不确定drAnimal的类型,可以执行以下操作:

var feedschedule_type=drAnimal[“feedschedule_type”]
Console.WriteLine(“feedschedule_类型为{0}”,typeof(feedschedule_类型))

基本上,您需要将其转换为int,然后使用标准转换,就像您在问题中所做的那样


最后,确保提要计划类型具有有效值。也就是说,确保它的值是0、1或2。

我最近在使用
SqlParameter
时遇到了这个问题

我猜
drAnimal[“feedschedule\u type”]
被存储为
SqlDbType.Int
对象。为了强制转换参数,我必须执行以下类似操作:

(int)(SqlDbType.Int)(drAnimal["feedschedule_type"]);

您可能需要使用类似的链来获取实际的int值,并将其强制到枚举中。

数据库中记录的数据类型是什么?我将其作为整数放在数据库中,尝试使用声明为var temp的临时变量从数据库读取返回值,然后使用调试器在尝试任何强制转换之前检查从数据库返回的值。谢谢,Tho Racil Hilan他的回答使其工作。我刚刚尝试过,但它抛出了相同的错误。是的,你是对的。但是,将db字段转换为整数的最佳方法是使用
convert.ToInt32(drAnimal[“feedschedule\u type]”)
(如果字段不可为空)。如果它可以为null,那么最好使用
drAnimal[“feedschedule\u type”]作为int?
。可能,但是如果类型从技术上讲是
SqlDbType.Variant
,那么
Convert
将失败,因此初始强制转换。