【发布时间】: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; }
}
【问题讨论】: