简体   繁体   English

没有隐式引用转换

[英]There is no implicit reference conversion

I have the following code which doesn't compile.我有以下无法编译的代码。 I can't figure out why.我不知道为什么。 Can someone please help?有人可以帮忙吗?

var mercedes = new Mercedes().WithEngine(new LargeEngine());
var volkswagen = new Volkswagen().WithEngine(new SmallEngine());

public class Mercedes : Car<LargeEngine>
{
}

public class Volkswagen: Car<SmallEngine>
{
}

public class Engine
{
}

public class LargeEngine : Engine
{
}

public class SmallEngine : Engine
{
}

public class Car<T> where T : Engine
{
    internal T? Engine { get; set; }
}

public static class ExtensionMethods
{
    public static TCar WithEngine<TCar>(this TCar car, Engine engine)
        where TCar : Car<Engine>
    {
        car.Engine = engine;

        return car;
    }
}

The code above doesn't compile with the error:上面的代码没有编译错误:

The type 'Mercedes' cannot be used as type parameter 'TCar' in the generic type or method 'ExtensionMethods.WithConfiguration(TCar, Engine)'.类型“Mercedes”不能用作泛型类型或方法“ExtensionMethods.WithConfiguration(TCar, Engine)”中的类型参数“TCar”。 There is no implicit reference conversion from 'Mercedes' to 'Car<Engine>'没有从“Mercedes”到“Car<Engine>”的隐式引用转换

What I understand is that 'Mercedes' type cannot be casted implicitly into 'Car<Engine>' type.我的理解是“Mercedes”类型不能隐式转换为“Car<Engine>”类型。 But I also cannot figure out a way to cast it explicitly.但我也想不出一种明确地转换它的方法。

Thanks!谢谢!

Modify the definition of the WithEngine extension method to take a generic type parameter that is constrained to the Car class, where T is a type parameter that is derived from the Engine class.修改 WithEngine 扩展方法的定义,以采用受限于 Car 类的泛型类型参数,其中 T 是从 Engine 类派生的类型参数。

public static class ExtensionMethods
{
    public static TCar WithEngine<TCar, TEngine>(this TCar car, TEngine engine)
        where TCar : Car<TEngine>
        where TEngine : Engine
    {
        car.Engine = engine;

        return car;
    }
}

Why?为什么?

Car<LargeEngine> does not inherit from Car<Engine> , and cannot be implicitly converted to it. Car<LargeEngine>不继承自Car<Engine> ,并且不能隐式转换为它。

Imagine if generic types did implement inheritance like this.想象一下,如果泛型确实实现了这样的继承。 Then we would be able to write the following code:那么我们就可以写出如下代码:

List<LargeEngine> largeEngines = new List<LargeEngine>();
List<Engine> allEngines = largeEngines;

// Uh-oh - this allows us to add a small engine to the list
allEngines.Add(new SmallEngine());

// The first item in the list is a SmallEngine, not a LargeEngine!
// What should this line do?
LargeEngine x = largeEngines[0];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM