加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 应用于通用枚举集合的Cast.Cast导致无效的强制转换异常

发布时间:2020-12-15 07:46:07 所属栏目:百科 来源:网络整理
导读:enum Gender { Male,Female }var k = new[] { Gender.Male }.Castint().ToList().Castint?().ToList(); //alrightvar p = new[] { Gender.Male }.Castint().Castint?().ToList(); //InvalidCastException 第二种情况的原因是什么?我知道我不能把一个盒装的
enum Gender { Male,Female }

var k = new[] { Gender.Male }.Cast<int>().ToList().Cast<int?>().ToList(); //alright

var p = new[] { Gender.Male }.Cast<int>().Cast<int?>().ToList(); //InvalidCastException

第二种情况的原因是什么?我知道我不能把一个盒装的枚举转换为int?直接,但我做了两个阶段的演员,即Cast< int> .Cast< int?>应该工作.

编辑:

考虑到以下工作,这是令人惊讶的:

object o = Gender.Male;
int i = (int)o; // so here the cast is not to an entirely different type,which works

解决方法

好的,我来找出原因,这仍然很奇怪.我应该检查Cast< T>首先实现自己!

这就是Cast< T>的方法.实施:

public static IEnumerable<TResult> Cast<TResult>(this IEnumerable source)
{
    IEnumerable<TResult> enumerable = source as IEnumerable<TResult>;
    if (enumerable != null)
    {
        return enumerable; // this is the culprit..
    }
    if (source == null)
    {
        throw Error.ArgumentNull("source");
    }
    return Enumerable.CastIterator<TResult>(source);
}

private static IEnumerable<TResult> CastIterator<TResult>(IEnumerable source)
{
    foreach (object current in source)
    {
        yield return (TResult)((object)current);
    }
    yield break;
}

现在的问题是第一个Cast< int>呼叫:

new[] { Gender.Male }.Cast<int>()

这里的来源为IEnumerable< TResult>其中source是new [] {Gender.Male}并且泛型方法中的TResult是int返回非null值(这基本上意味着(new [] {Gender.Male}是通用上下文中的IEnumerable< int>),因此它返回相同的可枚举的后面是Gender [],并且在下一个Cast< int?>调用中,执行实际的强制转换,从Gender到int?失败.至于为什么在通用上下文中发生这种情况,catch it in this question .

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读