为什么 Linq Cast<T>当我定义了隐式强制转换时操作失败? [英] Why does a Linq Cast<T> operation fail when I have an implicit cast defined?

查看:19
本文介绍了为什么 Linq Cast<T>当我定义了隐式强制转换时操作失败?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了两个类,其中一个在它们之间有一个隐式转换:

I've created two classes, with one of them having an implicit cast between them:

public class Class1
{
    public int Test1;
}

public class Class2
{
    public int Test2;

    public static implicit operator Class1(Class2 item)
    {
        return new Class1{Test1 = item.Test2};
    }
}

当我创建一个类型的新列表并尝试 Cast 时另一方面,它因 InvalidCastException 而失败:

When I create a new list of one type and try to Cast<T> to the other, it fails with an InvalidCastException:

List<Class2> items = new List<Class2>{new Class2{Test2 = 9}};
foreach (Class1 item in items.Cast<Class1>())
{
    Console.WriteLine(item.Test1);
}

然而,这很好用:

foreach (Class1 item in items)
{
    Console.WriteLine(item.Test1);
}

为什么在使用 Cast 时不调用隐式强制转换?

Why is the implicit cast not called when using Cast<T>?

推荐答案

因为通过 Reflector 查看代码,Cast 不会尝试采用任何隐式转换运算符(LINQ Cast 代码针对各种特殊情况进行了大量优化,但在那个方向上没有考虑)(因为许多 .NET 语言不会).

Because, looking at the code via Reflector, Cast doesnt attempt to take any implicit cast operators (the LINQ Cast code is heavily optimised for special cases of all kinds, but nothing in that direction) into account (as many .NET languages won't).

在没有涉及反射和其他事情的情况下,泛型在任何情况下都没有提供任何开箱即用的方法来考虑这些额外的东西.

Without getting into reflection and other things, generics doesnt offer any out of the box way to take such extra stuff into account in any case.

一般来说,像隐式/显式、等式运算符等更复杂的工具一般不会被像 LINQ 这样的通用工具处理.

In general, more complex facilities like implicit/explict, equality operators etc. are not generally handled by generic facilities like LINQ.

这篇关于为什么 Linq Cast&lt;T&gt;当我定义了隐式强制转换时操作失败?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆