2014-08-28 42 views
0

我有以下泛型方法,我想封装一些执行以下操作的逻辑:如果实例是ILookUp(这是我自己的通用接口类型) null,然后调用一个带有null参数的方法(如果不是null),然后使用接口中ID字段的值调用同一个方法。将泛型枚举参数强制为可空的时出现异常

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

但是,我得到一个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; } 
    } 

回答

1

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

以下应该工作。

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

​​
+0

大,现在它工作。第二行也给出错误,我不得不改变返回(Id?)(ValueType)DoEnumNullable(enumAsulong)返回(Id)(ValueType)DoEnumNullable(enumAsULong)使其工作。 – 2014-08-28 19:40:53

+0

我会阅读这个问题,看看我能理解为什么。 – 2014-08-28 19:42:40