【问题标题】:Exception when casting a generic enum parameter to nullable long将通用枚举参数转换为可为空的 long 时出现异常
【发布时间】:2014-08-29 03:40:27
【问题描述】:

我有以下通用方法,我想在其中封装一些执行以下操作的逻辑:采用 ILookUp 的实例(这是我自己的通用接口类型),如果该实例为 null,则调用带有 null 参数的方法,如果不为 null,则使用接口中 ID 字段的值调用相同的方法。

ID 字段始终是基于 ulong 的枚举类型。 ID 字段永远不会为空,我仍然想将其转换为可为空的类型。

但是,我在指示的语句上收到 InvalidCastException。奇怪的是,在 Watch 窗口中,演员工作正常。可能出了什么问题..?

   /// <summary>
   /// if not null, extracts an ID and snapshots it as a nullable ulong (ulong?)
   /// </summary>          
   public Id? SnapshotID<T, Id>(T instance)
     where T : ILookUp<T, Id>
     where Id : struct // is always an enum based on ulong
   {
      if (instance != null)
        {
            ulong? enumAsULong = (ulong?)((ValueType)instance.ID); // <- InvalidCastException here

            return (Id?)(ValueType)DoEnumNullable(enumAsULong);
        }
        else
        {
            return (Id?)(ValueType)DoEnumNullable((ulong?)null);
        }
    }

    public ulong? DoEnumNullable(ulong? val)
    {
        return DoUInt64Nullable(val);
    }

    public interface ILookUp<T,Id> 
        where T : ILookUp<T,Id>
        where Id : struct  // cannot specify enum - this allows nullable operations on       Id enums
    {

        Id ID { get; }
    }

【问题讨论】:

    标签: c# generics enums


    【解决方案1】:

    你不能那样做。 You can only cast a boxed value type to the same type or Nullable&lt;T&gt;。在这种情况下,您可以将其转换为 T? Nullable&lt;YourEnumType&gt;,但不能转换为其他类型。

    以下应该可以工作。

    ulong? enumAsULong = (ulong)((ValueType)instance.ID);
    

    ulong? enumAsULong = Convert.ToUInt64((ValueType)instance.ID);
    

    【讨论】:

    • 很好,现在可以使用了。第二行也给出了错误,我必须将 return (Id?)(ValueType)DoEnumNullable(enumAsULong) 更改为 return (Id)(ValueType)DoEnumNullable(enumAsULong) 才能使其工作。
    猜你喜欢
    • 1970-01-01
    • 2013-12-13
    • 2013-01-17
    • 1970-01-01
    • 1970-01-01
    • 2018-11-17
    • 2013-08-25
    • 2013-04-11
    • 1970-01-01
    相关资源
    最近更新 更多