我在 C# WPF 应用程序中遇到的 InvalidCastException 是如何发生的?
我尝试从“cacheConsumptionStatus = ConsumptionStatusType.GetByKey(Convert.ToInt32(value));”更改应该有问题的行 到“cacheConsumptionStatus = (ConsumptionStatusType.)value;”,结果是一样的。
结果甚至与完全注释掉的那行相同。
“cache”是 BitArray 类型,“hasValue”是 bool,“value”是 object。
相关代码:
消息.cs
...
switch(propID)
{
...
case 968:
cache[9] = hasValue;
if (hasValue)
{ <-- InvalidCastException -- Unable to cast object of type 'System.Int32' to type 'Enumerations.ConsumptionStatusType'.
cacheConsumptionStatus = ConsumptionStatusType.GetByKey(Convert.ToInt32(value));
}
videoManagerRef.events.FireOnMessageConsumptionStatus(this, cacheConsumptionStatus);
break;
...
消费状态类型.cs
using System.Collections.ObjectModel;
namespace Enumerations
{
public class ConsumptionStatusType : EnumBase<ConsumptionStatusType>
{
public static readonly ConsumptionStatusType CONSUMED = new ConsumptionStatusType(0, "CONSUMED");
public static readonly ConsumptionStatusType UNCONSUMED_SUPPRESSED = new ConsumptionStatusType(1, "UNCONSUMED_SUPPRESSED");
public static readonly ConsumptionStatusType UNCONSUMED_NORMAL = new ConsumptionStatusType(2, "UNCONSUMED_NORMAL");
public static readonly ConsumptionStatusType UNCONSUMED_ELEVATED = new ConsumptionStatusType(3, "UNCONSUMED_ELEVATED");
public ConsumptionStatusType(int key, string value)
: base(key, value)
{
}
public static ReadOnlyCollection<ConsumptionStatusType> GetValues()
{
return GetBaseValues();
}
public static ConsumptionStatusType GetByKey(int key)
{
return GetBaseByKey(key);
}
}
}