为什么一个LINQ演员LT; T>操作失败时,我有一个隐式转换定义的?我有一个、演员、定义、操作

2023-09-02 20:43:09 作者:我喜欢做事随本心。

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

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};
    }
}

当我创建一种新的列表,并尝试转换< T>其他时,出现一个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);
}

然而,这工作得很好:

This, however, works fine:

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

为什么隐式转换使用演员LT的时候不叫; T&GT;

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

推荐答案

由于,看着通过反射的code,投犯规的企图采取任何隐含的类型转换操作符(LINQ的演员code在很大程度上优化各类特殊情况,但没有朝那个方向)考虑在内(正如许多.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.